如何在 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
How to start and stop a timer in Java
提问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:
- It has stop() and restart() methods.
- Swing components should be updated on the Event Dispatch Thread.
- 它有 stop() 和 restart() 方法。
- Swing 组件应该在事件调度线程上更新。