简体   繁体   English

如何在Java中的特定时间停止计时器?

[英]How to stop a timer at a specific time in java?

I have made a timer in java that starts but I do not know how to stop it. 我已经在Java中启动了一个计时器,但是我不知道如何停止它。 Below is my code for the timer. 下面是我的计时器代码。

Timer timer = new Timer(1000, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
            label1.setText("Hello");        
    }

});
timer.start();

I want to add in few other texts when the timer reaches 500 and then stop the timer when it reaches 1000. 我想在计时器达到500时添加一些其他文本,然后在计时器达到1000时停止计时器。

"How to stop a timer at a specific time in java?" “如何在Java中的特定时间停止计时器?”

Just do this. 就是这样 Increment the count each fire of the timer event, if the count is at a certain point, then stop the timer, else set the text to the count 递增计时器事件的每次触发计数,如果计数在某个点,则停止计时器,否则将文本设置为计数

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();
}

The simplest way is to use multiple timers. 最简单的方法是使用多个计时器。 A better approach though is to use something like a ScheduledThreadPoolExecutor ExecutorService and you can then schedule as many Runnable s as you like to be executed with whatever timings you like... 不过,更好的方法是使用ScheduledThreadPoolExecutor ExecutorService类的东西,然后您可以调度任意数量的Runnable ,并在任意时间对其执行...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM