Search code examples
javaswingtimeractioneventjavax.swing.timer

Unable to execute timer in [java]


I've been trying to get down the basics of using a timer so that I can create a bouncing ball program, but I can't seem to implement a timer correctly. This program should in theory just continuously print the display, but instead the program simply terminates. What can I do to remedy this issue and fix the timer?

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


public class DisplayStuff {

public static void main(String[] args) {


    class TimerListener implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            System.out.println("Display me.");
        }
    }

    ActionListener listener = new TimerListener();
    Timer t= new Timer(1000, listener);
    t.start();

}
}

Solution

  • Your program has no Swing event thread with which to continue the Timer. You need to put it into a visualized Swing GUI to start the Swing event dispatch thread, and then start the timer. This could be achieved by something as simple as displaying a JOptionPane:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JOptionPane;
    import javax.swing.Timer;
    import javax.swing.JFrame;
    
    public class DisplayStuff {
    
       public static void main(String[] args) {
    
          class TimerListener implements ActionListener {
             public void actionPerformed(ActionEvent event) {
                System.out.println("Display me.");
             }
          }
    
          ActionListener listener = new TimerListener();
          Timer t = new Timer(1000, listener);
          t.start();
    
          // ***** add just this *****
          JOptionPane.showMessageDialog(null, "foo");
    
       }
    }