JAVA: 启动定时器,在 0 秒停止定时器,重新启动定时器

JAVA: start timer, stop timer at 0 seconds, restart timer

私有代码位于 Jbutton 中,该按钮在单击鼠标时启动计时器。当经过的时间等于原始时间时,底部附近的 if 语句不会停止计时器,但不会。我该如何解决?此外,当我按下按钮时,计时器会以更快的速度加速。

import java.awt.*;
import java.util.*;


public class refractiveIndex extends javax.swing.JFrame {

public static int time = 10;
public static int elapsedTime = 0;

private void nextQActionPerformed(java.awt.event.ActionEvent evt) { 

time = 10;
elapsedTime = 0;                                     

    final Timer timer = new Timer();
    TimerTask task = new TimerTask()
    {
        public void run()
                {
                    elapsedTime++;//amount of time passed
                    timeLeft.setText("" + (time - elapsedTime));//int 'time' = 0 (this is time left)
                }
    };

    if(time - elapsedTime == 0)
    {
        timer.cancel();//timer stops after 5 secs
        score1 = 0;//resets score
        question.setText("GAME OVER");
    }

    timer.scheduleAtFixedRate(task, 500, 500);//.5 second delay, rate of .5 second

您可以调整您的习惯 TimerTask

TimerTask task = new TimerTask() {
    public void run() {
        elapsedTime++;//amount of time passed
        timeLeft.setText("" + (time - elapsedTime));

        if (time - elapsedTime == 0) {
            cancel();
            score1 = 0;//resets score
            question.setText("GAME OVER");
        }
    }
};

另见 this question