James anderson James anderson - 1 month ago 10
Java Question

Swing Timer issue - stop Timer

I have been trying to stop the timer and solve this for days now, unfortunately no luck, hope someone will be able to help.

The idea is to use the timer to click a button which increases the value in the text field so I have the timer in the start button and I wish to stop it in the stop button.

That's the code I have behind my start button:

private void btStartTimerActionPerformed(java.awt.event.ActionEvent evt) {

javax.swing.Timer tm = new javax.swing.Timer(100, new ActionListener(){
public void actionPerformed(ActionEvent evt) {

btAddOneActionPerformed(evt);
}
});
tm.start();


}

private void btStopTimerActionPerformed(java.awt.event.ActionEvent evt) {

}

Answer

You've got a problem of scope in your posted code: your Timer variable, tm, is declared within your start button's actionPerformed method and thus is only visible within that method. So you cannot get a viable reference to it when outside of that method. A solution is to declare the variable on the class level as a private instance (non-static) variable, and only call start() on it within your start button's action listener. This will make the variable visible throughout your class, and the stop button's listener should be able to call its methods.

e.g.,

package pkg3;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.Timer;

public class TimerDeclaration {
    private static final int DELAY = 1000;

    // the tm2 variable is visible throughout the class
    private Timer tm2 = new Timer(DELAY, new TimerListener());

    private JButton btStartTimer1 = new JButton("Start Timer 1");
    private JButton btStartTimer2 = new JButton("Start Timer 2");

    public TimerDeclaration() {
        btStartTimer1.addActionListener(e -> btStartTimer1ActionPerformed(e));
        btStartTimer2.addActionListener(e -> btStartTimer2ActionPerformed(e));
    }

    private void btStartTimer2ActionPerformed(ActionEvent e) {
        tm2.start(); // tm2 is visible throughout your program
    }

    private void btStartTimer1ActionPerformed(ActionEvent e) {
        javax.swing.Timer tm = new javax.swing.Timer(100, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {

                // btAddOneActionPerformed(evt);
            }
        });
        tm.start(); // this is only visible inside here!!!
    }

    private class TimerListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub

        }
    }
}