Reputation: 7
I am working on this reaction time game that tells you to click an arrow key once the ball has turned into a different colored ball. However, I can't seem to get the image of the ball to be replaced by the other ball.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.Timer;
public class Game extends JPanel
{
private JLabel watch, main;
private ImageIcon constant, react;
final int width = 600;
final int height = 600;
private Timer replace;
private ActionListener timerListener;
public Game()
{
setPreferredSize(new Dimension(width, height));
setBackground(Color.black);
watch = new JLabel("Click Up Arrow when you see a blue ball");
watch.setForeground(Color.white);
add(watch);
constant = new ImageIcon("constantCircle.png");
main = new JLabel(constant);
replace = new Timer(3000, timerListener);
replace.setRepeats(false);
replace.start();
add(main);
}
public void actionPerformed (ActionEvent e)
{
react = new ImageIcon("reactCircle.png");
main.setIcon(react);
}
}
This is the code for my display and I wanted to use a swing timer to replace the image after 3 seconds
This is what I want it to look like before
and this is what I want it to look like after 3 seconds
Upvotes: 0
Views: 90
Reputation: 11153
You're never initializing timerListener
private ActionListener timerListener;
Inside your constructor you have to call (With Java 8 lambdas):
timerListener = e -> {
react = new ImageIcon("reactCircle.png");
main.setIcon(react);
}
Or (Java 7 and lower):
timerListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
react = new ImageIcon("reactCircle.png");
main.setIcon(react);
}
}
And don't forget to call timerListener.stop()
once the timer has fired, so that you don't keep computing more times
From Andrew Thompson's comment below:
As you only want to replace the image once, call timerListener.setRepeats(false)
on your constructor. Check the docs for more information about it.
Upvotes: 1