微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过计时器替换图像一次

如何解决通过计时器替换图像一次

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

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 秒后使用摆动计时器替换图像

这是我之前想要的样子

This is what I want it to look like before

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

and this is what I want it to look like after 3 seconds

解决方法

您永远不会初始化 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 了解更多信息。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。