Reputation: 1003
I'm trying to create a little button game for a school project. What the game is, is there are a couple buttons that every like 3 seconds will flash a color then if you press it when the color is up, it stays that color.
I have all the buttons created and they display just fine. I just need help with the actual handling code.
What I'm getting stuck on
timer = new Timer(length, jButton1ActionPerformed);
timer.setInitialDelay(pause);
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jButton1.setBackground(Color.blue);
}
Now this isn't my actual game, I'm just trying to get the hang of the Swing Timers
Now that I have the button changing colors this is the code that I tried to get it to stay that color when clicked.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jButton1.getBackground().equals(Color.blue){
jButton1.setBackground(Color.blue);
timer.stop();
}
}
Upvotes: 1
Views: 1600
Reputation: 285405
You will want to use a Swing Timer to handle your animation. In the Timer's ActionListener, you would have code that randomly selects a button (the Random class can help here) and changes its color, possibly via setForground(...)
, or even by using ImageIcons and swapping icons via setIcon(...)
. The JButton's ActionListener can then check the button's icon or foreground color and act accordingly.
Since this is a school project, I'm not posting a code solution but will add some links that should help:
To create an ActionListener for your Timer, do just that -- create one inline:
ActionListener timerListener = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// code to be performed every xxx mSec goes here
}
}
int timerDelay = 3 * 1000; // or whatever length of time needed
Timer timer = new Timer(timerDelay, timerListener);
// later on in the block where you want to start your Timer
timer.start();
Upvotes: 2