I have made a timer in java that starts but I do not know how to stop it. 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.
"How to stop a timer at a specific time in 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...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.