[英]Stop a timer with a button
I have a start button that starts a timer with a loop. 我有一个启动按钮,可以循环启动计时器。
public synchronized void startTourButtonActionPerformed(java.awt.event.ActionEvent evt) {
new java.util.Timer().schedule(new java.util.TimerTask() {
@Override
public void run() {
try {
byte st = presetNo[count];
System.out.println("Start Tour Button pressed, String: " + st);
// this part will run from 0 to max of presets every
// counting.
count++;
if (count >= MaxCount)
count = 0;
byte[] command = { (byte) startTx, address, byteOne, goPreset, 0x00, st, endTx, 0x0F };
TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(
twoWaySerCom.serialPort.getOutputStream());
sw.out.write(command);
}
catch (IOException e) {
e.printStackTrace();
}
}
}, 100, 5000);
}
And I have another 'Stop' Button. 我还有另一个“停止”按钮。 Currently i am stopping the loop by breaking it and getting an Exception.
目前,我正在通过中断循环并获取异常来停止循环。 Obviously not the correct procedure and also stops the start button from working.
显然这不是正确的过程,并且还会停止启动按钮的工作。
public synchronized void stopTourButtonActionPerformed(java.awt.event.ActionEvent evt){
count = -1;
}
My question is how do i stop it correctly so that i can restart afterwards? 我的问题是如何正确停止它,以便以后可以重新启动?
Just keep a reference of the timer (a variable) and call the cancel()
method. 只需保留计时器的引用(变量)并调用
cancel()
方法即可。
In startTourButtonActionPerformed
在
startTourButtonActionPerformed
//...
timer = new java.util.Timer();
timer.schedule(new java.util.TimerTask() {
//...
In stopTourButtonActionPerformed
在
stopTourButtonActionPerformed
timer.cancel();
Note the it will cancel all your timer
's tasks. 请注意,它将取消您所有
timer
的任务。 There is also a cancel()
method on a TimerTask if you want to precisely stop only one single task. 如果只想停止一个任务,则在TimerTask上还有一个
cancel()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.