Search code examples
javatimerbluej

Timer Delay Not Working?


I am trying to make this program print the current time in the console every second.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
import java.util.Date;

public class E10U27 extends JFrame {
    public static void main(String[] args){

   // Prep the listener to respond
   class TimerListener implements ActionListener {
      public void actionPerformed(ActionEvent event) {

         Date now = new Date();
         System.out.println(now);
      }
   }

   ActionListener listener = new TimerListener();
   final int DELAY = 1000; 
   Timer t = new Timer(DELAY, listener);
   t.start();    
}
}

However, it prints like 50 of just a single time (ex. 2:52 50 times), and so on. It does tick correctly though. How to make it run correctly? Are there any mistakes in my code?


Solution

  • I ran the code without errors, but it finished without showing the date in the interval assigned to Timer, so I made some changes

    1. Change the DELAY to 1000 (1 second) to print the current time every second

    final int DELAY = 1000;

    1. Create the frame to make the program keep running, otherwise the main method will finish (new E10U27()).setVisible(true);

    This is the program with the modifications, it prints the current time every second:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.Timer;
    import java.util.Date;
    
    public class E10U27 extends JFrame {
        public static void main(String[] args){
    
            // Prep the listener to respond
            class TimerListener implements ActionListener {
                public void actionPerformed(ActionEvent event) {
    
                    Date now = new Date();
                    System.out.println(now);
                }
            }
    
            ActionListener listener = new TimerListener();
            final int DELAY = 1000; // Milliseconds between timer ticks
            Timer t = new Timer(DELAY, listener);
            t.start();
    
            (new E10U27()).setVisible(true);
        }
    }