英文:
Can't stop timer repeats inside Actionlistener in Java
问题
我有一个简单的倒计时,每隔几毫秒检查一次变量是否为false。
当它为false时,计时器应该停止。但是对我来说它不起作用。为什么?我应该如何修复这个问题?我尝试了在其他主题中找到的多种方法,但似乎没有一个有效。
final Timer countdown = new Timer(10, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (Fight.isStatus() == false) {
((Timer)evt.getSource()).stop();
((Timer)evt.getSource()).setRepeats(false);
}
}
});
countdown.setRepeats(true);
countdown.start();
英文:
I hava a simple countdown that checks every few Milliseconds if a variable is false.
When it is false, the timer should be stopped. But it does not work for me. Why? And how would I fix this? I tried multiple ways I found in other threads, but none seem to work.
> final Timer countdown = new Timer(10, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (Fight.isStatus()== false) {
((Timer)evt.getSource()).stop();
((Timer)evt.getSource()).setRepeats(false);
}
}
});
countdown.setRepeats(true);
countdown.start();
答案1
得分: 0
你可以使用你的任务创建一个 TimerTask
实例。TimerTask task = new YourTask();
然后调用 task.cancel();
我不知道如何在你的代码中使用 cancel 方法。
英文:
You can create a TimerTask
instance with your task. TimerTask task = new YourTask();
And say task.cancel();
I do not know how to use cancel method in your code.
专注分享java语言的经验与见解,让所有开发者获益!
评论