如何在Java中正确处理计时器? [英] How to handle Timers correctly in Java?
本文介绍了如何在Java中正确处理计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望我的计时器仅在5秒内一次执行一次actionPerformed方法,但是它多次在控制台 Hello中写入内容:
I want my timer to execute the actionPerformed method only one time once it 5 seconds the time but it is writing in the console "Hello" lots of times:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class X{
public static void main(String args[]) {
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println( "Hello" );
}
};
Timer timer = new Timer( 5000, actionListener );
timer.start();
}
}
如何获得想要的效果?谢谢
How can I make the effect I want? Thanks
推荐答案
如上所述,最好使用 java.util.Timer
,但您也可以使用 setRepeats()开始之前:
As already mentioned, it's better to use java.util.Timer
, but you can also use setRepeats() before starting:
timer.setRepeats(false);
这篇关于如何在Java中正确处理计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文