[英]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.