4

I am trying to print a statement repeatedly using Swing Timer but the statement doesn't gets printed !

What's the mistake I am making ?

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

    public class SwingTimer implements ActionListener {

        Timer timer;

        public static void main(String[] args) {
            SwingTimer obj = new SwingTimer();
            obj.create();
        }

        public void create() {
            timer = new Timer(1000, this);
            timer.setInitialDelay(0);
            timer.start();
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Hello using Timer");
        }    
    }
Snehasish
  • 1,051
  • 5
  • 20
  • 37
  • 1
    funny how [similar problems](http://stackoverflow.com/q/14900697/203657) tend to creep up at the same time :-) – kleopatra Feb 17 '13 at 13:20

2 Answers2

2

The javax.swing.Timer probably starts as a daemon thread: it doesn't keep the jvm alive, your main ends, the jvm exits. It post the timer events to the GUI event queue which starts when the first dialog or frame is made visible.

You have to create a JFrame, and make it visible or use the java.util.Timer if you don't need windowing system at all.

The following code shows how to use java.util.Timer:

import java.util.Timer;
import java.util.TimerTask;

public class TimerDemo extends TimerTask {

   private long time = System.currentTimeMillis();

   @Override public void run() {
      long elapsed = System.currentTimeMillis() - time;
      System.err.println( elapsed );
      time = System.currentTimeMillis();
   }

   public static void main( String[] args ) throws Exception {
      Timer t = new Timer( "My 100 ms Timer", true );
      t.schedule( new TimerDemo(), 0, 100 );
      Thread.sleep( 1000 );              // wait 1 seconde before terminating
   }
}
Aubin
  • 14,617
  • 9
  • 61
  • 84
2

javax.swing.Timer should only be used when using Swing applications. Currently your main Thread is exiting as the Timer uses a daemon Thread. As a workaround you could do:

public static void main(String[] args) {

   SwingTimer obj = new SwingTimer();
   obj.create();
   JOptionPane.showMessageDialog(null, "Timer Running - Click OK to end");
}

An alternative for non-UI applications is to use ScheduledExecutorService

Reimeus
  • 158,255
  • 15
  • 216
  • 276