简体   繁体   中英

Cant get Java Timer working (javax.swing.Timer)

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM