简体   繁体   English

无法使Java Timer工作(javax.swing.Timer)

[英]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. 因此,我试图学习javax.swing.Timer的工作方式,但是我无法通过它进行简单的操作。 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. 基本上我想做的就是让系统每秒打印出“ test2”,但是似乎从未调用过actionPerformed方法。 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 测试1测试3测试4测试5测试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. 添加一个Thread.currentThread().sleep(10000) ,您将看到计时器事件。

A timer does not force your program to continue running after the main method has finished. 在main方法完成后,计时器不会强制您的程序继续运行。 Without starting another thread to run or ensuring that the main thread runs for a sufficient amount of time, the timer may never trigger. 如果不启动另一个线程来运行或确保主线程运行足够的时间,则计时器可能永远不会触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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