通过计时器替换图像一次

Replacing an image once through timer

我正在研究这个反应时间游戏,它告诉你一旦球变成不同颜色的球就点击箭头键。但是,我似乎无法得到要被另一个球替换的球的图像。

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 秒后替换图像

这是我之前想要的样子

这就是我希望它在 3 秒后的样子

你永远不会初始化 timerListener

private ActionListener timerListener;

在您的构造函数中,您必须调用(使用 Java 8 个 lambda):

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(),这样您就不会继续计算更多次

来自 Andrew Thompson 的以下评论:

由于您只想替换图像一次,因此请在构造函数中调用 timerListener.setRepeats(false)。查看 docs 了解更多信息。