【问题标题】:Replacing an image once through timer通过计时器替换图像一次
【发布时间】:2021-05-18 13:26:32
【问题描述】:

我正在开发这款反应时间游戏,它告诉您在球变成不同颜色的球后单击箭头键。但是,我似乎无法将球的图像替换为另一个球。

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 秒后的样子

【问题讨论】:

  • 为了更好的帮助,请尽快发布正确的minimal reproducible example,你的timerListener呢?
  • 我刚刚编辑了代码以显示我的所有代码,以显示 timerListener 的位置。另外,我会尽量减少代码量,但老实说,我真的不知道问题出在哪里。我认为它在计时器中,但我只是不确定如何用新图像替换图像@Frakcool
  • 你在哪里初始化timerListener?到目前为止,您的 actionPerformed 不属于任何东西。以this answer 为起点。在您当前的代码中,replace = new Timer(3000, timerListener);replace = new Timer(3000, null); 相同
  • ohhhhh,好的,非常感谢。我只是这样做了,它奏效了!谢谢@Frakcool
  • 在下面查看我的答案

标签: java swing timer jframe imageicon


【解决方案1】:

你永远不会初始化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()打电话,这样你就不会继续计算更多次了

来自 Andrew Thompson 下面的评论:

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

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多