Reputation: 21
imagine an array of numbers. Specific number-specific button, which has to blink. I have to go through the array. Now swing timer blinks one button ok, but if I try to put for(int I=0;i<array.length;i++)
loop to go to next button - Timer does not do it. Any help would be appreciated. Thank you. Here is the code I have now:
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
Upvotes: 0
Views: 2022
Reputation: 36611
Your logic seems faulty. What you want is:
Where a blink is
This means you are probably better off with two Timer
instances.
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();
Something along the lines of the above code should do it. Note how:
BlinkingTimer
variable)BlinkingTimer
uses setRepeats( false )
as it only needs to be triggered onceLightTimer
uses setRepeats( true )
as it needs to execute multiple times, and turns itself off once it let all lights blinkUpvotes: 1