gpt4 book ai didi

Java定时器对象错误: Timer already cancelled

转载 作者:行者123 更新时间:2023-11-30 05:53:28 25 4
gpt4 key购买 nike

我有一个 JButton,按下时会启动倒计时器。当我按下按钮时,它开始,当我再次按下它时(按钮会说“停止”),它停止。但是,当我再次按下它再次开始计时时,我收到一条错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Timer already cancelled.

这是我的代码:

    final static Timer t = new Timer();

static void startTimer(JButton b) {

t = new Timer(); // Solved: I needed to create a new Timer object.

t.scheduleAtFixedRate(new TimerTask() {

double timeleft = calcShutterSpeed;

@Override
public void run() {
String s = secondsToMinutes(timeleft);
time.setText(s);
timeleft--;
if (timeleft < 0) {
t.cancel();
b.setText("START TIMER");
b.setForeground(Color.BLACK);
}
}
}, 0, 1000);
}

static void stopTimer() {
t.cancel();
}

/**
* Creates the timer if "Start" is pressed.
*
* @param b
*/
static void timer(JButton b) {
b.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

// If start button is pressed, change text to display stop
if (b.getText() == "START TIMER") {
startTimer(b);
b.setText("STOP TIMER");
b.setForeground(Color.RED);
}
// If stop button is pressed, cancel timer and change text to start
else if (b.getText() == "STOP TIMER") {
stopTimer();
b.setText("START TIMER");
b.setForeground(Color.BLACK);
}
}
});
}

任何可以解决此问题的提示或建议将不胜感激。提前致谢!

编辑:对于好奇的人来说,修复真的非常简单。修复在代码中。

最佳答案

我认为计时器上的“取消”方法仍然使计划任务保持取消状态。在取消之后立即调用“purge”方法应该清理队列,也许可以解决这个问题。

关于Java定时器对象错误: Timer already cancelled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53546654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com