无法在Java的ActionListener内停止定时器重复。

huangapple 未分类评论51阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年7月27日 15:57:54
  • 转载请务必保留本文链接:https://java.coder-hub.com/63111014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定