[英]How to stop a timer at a specific time in java?
我已经在Java中启动了一个计时器,但是我不知道如何停止它。 下面是我的计时器代码。
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
label1.setText("Hello");
}
});
timer.start();
我想在计时器达到500时添加一些其他文本,然后在计时器达到1000时停止计时器。
“如何在Java中的特定时间停止计时器?”
就是这样 递增计时器事件的每次触发计数,如果计数在某个点,则停止计时器,否则将文本设置为计数
int count = 0;
JLabel label = new JLabel(String.valueOf(count));
public Constructor() {
Timer timer = new Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (count >= 100) {
((Timer)e.getSource()).stop();
} else {
label.setText(String.valueOf(count));
count++;
}
}
});
timer.start();
}
最简单的方法是使用多个计时器。 不过,更好的方法是使用ScheduledThreadPoolExecutor
ExecutorService
类的东西,然后您可以调度任意数量的Runnable
,并在任意时间对其执行...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.