想象一组数字。特定于数字的按钮,必须闪烁。我必须通过阵列。现在摆动计时器闪烁一个按钮确定,但如果我尝试将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
答案 0 :(得分:1)
你的逻辑似乎有缺陷。你想要的是:
眨眼是
这意味着您可能最好使用两个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 )
,因为它需要执行多次,并在所有灯光闪烁后自动关闭