如何在 Java 中启动和停止计时器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38033899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:56:04  来源:igfitidea点击:

How to start and stop a timer in Java

javatimer

提问by Eddie

I am not very good at Java...

我不太擅长Java...

I am working on a stopwatch, with a start, stop and reset button.

我正在制作一个带有开始、停止和重置按钮的秒表。

When u press start, it obviously starts. When u press stop, it pauses( using timer.cancel();). When u press reset it makes all the values 0, and stops. and when u press start again, it should continue to count, where it was stopped(unless it was reset).

当你按开始时,它显然开始了。当您按停止时,它会暂停(使用timer.cancel();)。当你按下复位键时,它会使所有值变为 0,然后停止。当你再次按下开始时,它应该继续计数,它在哪里停止(除非它被重置)。

I am using a java.util.timer;So here is the question: How do you start a timer, that was paused(canceled)? For example, if I used the stop button to stop it. And in my code it would look like this: timer.cancel();, how can I start it again??

我正在使用一个java.util.timer;所以这里的问题是:你如何启动一个暂停(取消)的计时器?例如,如果我使用停止按钮来停止它。在我的代码中,它看起来像这样:timer.cancel();,我怎样才能再次启动它?

I know that you can do this using timer.stop()and timer.start()in vb

我知道你可以使用timer.stop()timer.start()vb

 import java.util.Timer;
 import java.util.TimerTask;

public static void timerStart()
{

        //timer
        if(running == false)
        {

            TimerTask task = new TimerTask()
            { 


                public void run()
                {
                    //what to do at each excecution
                    seconds++;
                    lbl.setText(Short.toString(seconds));
                }
            };

        timer.scheduleAtFixedRate(task,1000,1000);
        }
        running = true;
}

and

 public static void timerStop()
 {
    timer.cancel();
    runnig = false;
 }

采纳答案by camickr

I am using a java.util.timer;

我正在使用 java.util.timer;

Well you should be using a Swing Timerfor a couple of reasons:

好吧,出于以下几个原因,您应该使用Swing Timer

  1. It has stop() and restart() methods.
  2. Swing components should be updated on the Event Dispatch Thread.
  1. 它有 stop() 和 restart() 方法。
  2. Swing 组件应该在事件调度线程上更新。