0

I have this current code written in my program that is supposed to start the timer, however the code does not work. The timer does not start and I'm pretty sure that I missed something out.

private Timer timer; 

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

    timer = new Timer(5000,new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent evt) {

        }
    });

    StartStopTimer.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (!timer.isRunning()) {
                timer.start(); AddOneActionPerformed(evt);
            } else {
                timer.stop();
            }
        } 
    });
}                                  

The private class is right at the top of my program and the rest of the code is located in a button.

Niral Mehta
  • 63
  • 1
  • 2
  • 11
  • 1
    You're creating a Timer object inside of the StartStopTimerActionPerformed method, but the Timer does nothing, has an empty actionPerformed method and is never started. Then you're adding an ActionListener to some entity (another Timer?) but not starting it. Have you gone through the [Swing Timer tutorial](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) on this? – Hovercraft Full Of Eels Nov 02 '14 at 20:44
  • 1
    Please consider creating and posting a small but simple complete program that illustrates your problem, an [MCVE](http://stackoverflow.com/help/mcve). Please check the link for the details of this very useful tool. – Hovercraft Full Of Eels Nov 02 '14 at 20:45
  • 1
    Every time StartStopTimerActionPerformed is called, you create another instance of Timer, and then add another ActionListener to StartStopTimer...Consider providing a runnable example which demonstrates your problem – MadProgrammer Nov 02 '14 at 20:46
  • There's a complete example [here](http://stackoverflow.com/a/9852739/230513). – trashgod Nov 03 '14 at 01:42

0 Answers0