[英]Java Swing Timer Loop
想象一个数字数组。 特定号码特定按钮,该按钮必须闪烁。 我必须遍历数组。 现在,swing计时器会按一个按钮闪烁一次,但是如果我尝试将for(int I=0;i<array.length;i++)
循环到下一个按钮-计时器不会执行此操作。 任何帮助,将不胜感激。 谢谢。 这是我现在拥有的代码:
Timer startGame = new Timer(1000, new ActionListener() {
int colorPlay = 1;//which sqaure to blink
int blinkingState = 0;
@Override
public void actionPerformed(ActionEvent e) {
if (blinkingState < 2) {
int i = blinkingState % 2;
switch (i) {
case 0:
if (colorPlay == 1) {
greenButton.setBackground(Color.green);
} else if (colorPlay == 2) {
redButton.setBackground(Color.red);
} else if (colorPlay == 3) {
blueButton.setBackground(Color.blue);
} else if (colorPlay == 4) {
yellowButton.setBackground(Color.yellow);
}
break;
case 1:
if (colorPlay == 1) {
greenButton.setBackground(lightGreen);
} else if (colorPlay == 2) {
redButton.setBackground(lightRed);
} else if (colorPlay == 3) {
blueButton.setBackground(lightBlue);
} else if (colorPlay == 4) {
yellowButton.setBackground(lightYellow);
}
break;
}//switch ends
blinkingState++;
}//if blinking<2 ends
}//actionPerformed ends
});//timer ends
您的逻辑似乎有问题。 您想要的是:
眨眼的地方
这意味着您最好使用两个Timer
实例。
Timer lightTimer = new Timer( 2000, new ActionListener(){
private int lightCounter = 0;
@Override
public void actionPerformed(ActionEvent e){
switch( lightCounter ){
case ...:
final JButton lightButton = ...;
lightButton.setBackground( regularColour );
Timer blinkingTimer = new Timer( 1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
lightButton.setColor( lightColour );
}
}
blinkingTimer.setRepeats( false );
blinkingTimer.start();
}
lightCounter++;
if ( lightCounter == numberOfLights ){
((Timer)e.getSource()).stop();
}
}
} );
lightTimer.setRepeats( true );
lightTimer.start();
上面的代码应该可以做到这一点。 注意如何:
BlinkingTimer
变量) BlinkingTimer
使用setRepeats( false )
,因为它只需要进行一次触发 LightTimer
使用setRepeats( true )
,并在所有指示灯闪烁后自动关闭
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.