Stopping a Swing Timer?
843785Jan 21 2009 — edited Jan 21 2009I have a simple code that starts a timer. The actionlistener contains stuff that works and I can start the timer with a push of a button. I can also quit the program with push of another button using System.exit(). What I seem not able to do is to simply stop the timer from a button push. I know the stop command and if/else routines does work but, it appears once the timer starts, it just keeps running and won't allow an interrupt/stop command.
I have read all about timers but find nothing that helps... any helpful input is appreciated - thanks,
Here's snippets of the relevant code:
This calls the routines to start and stop
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int onoff = 0; // 0 to start timer
clockSub(onoff); // call the clock subroutine
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int onoff=1; // 1 to stop timer
clockSub(onoff);
These are the action, start and stop routines:
class ClockListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
(the stuff inside the action routine works great...- no problems.
it just calls calendar and prints the time to a jLabel)
}
These routines start and (should) stop the timer:
public void clockSub(int onoff) {
javax.swing.Timer timely = new javax.swing.Timer(0,new ClockListener());
if(onoff ==0) { // 0 to start timer
timely.start();
}
else if(onoff == 1) { // 1 to stop timer
timely.stop();
}
}