问题描述
我正在开发这个反应时间游戏,它会告诉您在球变成不同颜色的球后单击箭头键。但是,我似乎无法将球的图像替换为另一个球。
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);
}
}
这是我之前想要的样子
这就是我希望它在 3 秒后的样子
解决方法
您永远不会初始化 timerListener
private ActionListener timerListener;
在您的构造函数中,您必须调用(使用 Java 8 lambdas):
timerListener = e -> {
react = new ImageIcon("reactCircle.png");
main.setIcon(react);
}
或(Java 7 及更低版本):
timerListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
react = new ImageIcon("reactCircle.png");
main.setIcon(react);
}
}
并且不要忘记在计时器触发后调用 timerListener.stop()
,这样您就不会继续计算更多次
来自以下安德鲁汤普森的评论:
由于您只想替换图像一次,请在构造函数上调用 timerListener.setRepeats(false)
。查看 docs 了解更多信息。