tags:

views:

358

answers:

2

So I'm trying to learn how the javax.swing.Timer works, but I can't get it to do a simple operation. Basically all I'm trying to do is have the system print out "test2" every second, but it seems the actionPerformed method is never called. What am I doing wrong?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public class Main 
{
    public static void main(String[] args)
    {
     System.out.println("test 1");

     final Other o = new Other();

     class TimerListener implements ActionListener
     {
      public void actionPerformed(ActionEvent e) 
      {
          System.out.println("test2");
      }    
     }
     //test
     System.out.println("test 3");

     ActionListener listener = new TimerListener();

     //test
     System.out.println("test 4");

     final int DELAY = 1000;
     Timer t = new Timer(DELAY, listener);

     //test
     System.out.println("test 5");

     t.start();

     //test
     System.out.println("test 6");
    } 
}

This is the output that the above code produces:

test 1 test 3 test 4 test 5 test 6

Thank you!

A: 

The program is exiting before the timer gets a chance to fire. Add a Thread.currentThread().sleep(10000) and you'll see the timer events.

ColinD
Thanks, that did the trick!
Olegious
You also should not use `javax.swing.Timer` off the EDT (strangely).
Tom Hawtin - tackline
A: 

A timer does not force your program to continue running after the main method has finished. Without starting another thread to run or ensuring that the main thread runs for a sufficient amount of time, the timer may never trigger.

unholysampler