Reputation: 1003
I'm creating a little "Game" where you have to click buttons that flash a color and if you press it while the color is still on the button, the button stays that color. So far I have the timers setting the colors on and off but I'm having trouble stopping the timer if the button is pressed. This is my code so far.
//Changes To The Colors
ActionListener timerListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
jButton1.setBackground(Color.blue);
}
};
int timerDelay = 1750;
Timer timer = new Timer(timerDelay, timerListener);
//Changes Colors Back To Default
ActionListener defaultTime = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
jButton1.setBackground(null);
}
};
int waiter = 1000;
Timer defaultState = new Timer(waiter, defaultTime);
timer.start();
timer.setRepeats(true);
defaultState.start();
defaultState.setRepeats(true);
And seen as I'm using Netbeans I added in the ActionPerformed option this is where I am getting the issues. It's not letting me call the timer.stop();
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jButton1.getBackground().equals(Color.blue)){
jButton1.setBackground(Color.blue);
timer.stop();
defaultState.stop();
}
}
Right now I'm only using one button just to get the hang of the whole swing timer thing
Upvotes: 2
Views: 516
Reputation: 2656
When you are running this code jButton1
's color is blinking. Once blue and once default. jButton1ActionPerformed()
in this method you are going to stop the timer if button's background color is blue(if(jButton1.getBackground().equals(Color.blue))
). This is not true when the button is default(It's set default, because you are setting the color null
). It's blinking because timer is repeating. If the button is blue, you can stop the timer without any trouble.
If the background color is null, if(jButton1.getBackground().equals(Color.blue))
condition is false. That's why your times isn't stop.
Click the button when it's background is blue. Your timer will be stopped.
If you need to stop the timer with the button color,
ActionListener timerListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
jButton1.setBackground(Color.blue);
timer.stop();
defaultState.stop();
}
};
Hope this helps.
Upvotes: 2