有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing能否取消Java中的特定TimerTask?

我正在创建一个游戏,如果你在计时器达到零的时候还没有达到某个点,游戏就会结束。它目前可以工作,我可以一次创建多个TimerTask,但我不能取消它们。当前,单击按钮重置计时器(在显示屏上),但仍将在后台运行,并在程序达到零时结束程序(即使它不应运行)。下面是启动每个计时器的ActionListener的代码

public class Game implements Runnable {

    private int currentScore, difficulty, level, highscore, x, y;
    private boolean playMusic, playClicks, gameRunning;
    private boolean stopLastTimer = false;
    JFrame gameFrame;
    Data data;
    JButton target;
    Thread t;
    JLabel score;
    Timer globalTimer = new Timer();
    JLabel timer;

    ActionListener clickedAction = new ActionListener(){
            public void actionPerformed(ActionEvent ae) {
               stopLastTimer = true;
               t.interrupt(); 
               currentScore++;
               score.setText("Score: " + currentScore);
               //playClickSound();
               globalTimer.schedule(new TimerTask(){

                   double second = 2.0;
                   @Override
                   public void run() {
                       second = second - 0.1;
                        if(stopLastTimer) { 
                        this.cancel(); stopLastTimer = false; } //should end old timer here
                        if(second == 0.0) {
                        this.cancel();
                        gameStop();
                       }
                       second = limitPrecision(Double.toString(second), 1);
                    timer.setText(second + "s");
                   }   
               },0, 100);

            }
        };

共 (1) 个答案

  1. # 1 楼答案

    不要使用计时器任务

    相反,你应该使用javax.swing.Timer作为动画。Swing计时器有一个stop()方法

    ActionEvent的源将是计时器本身

    阅读Swing教程中关于How to Use Timer的部分,了解更多信息和工作示例