actionListener 接口 actionPerformed 方法不适用于 Timer class

actionListener interfaces actionPerformed method not working with Timer class

下面的程序假设每隔一秒打印一次日期。但是,由于已知原因,这不起作用。

我已经在下面class和actionPerformed方法中实现了ActionListener接口:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

public class CurrentTimePrinter implements ActionListener{

        public void actionPerformed(ActionEvent e){
        System.out.println(new Date());

    }
}

这是测试人员class:

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


public class CurrentTimePrinterTester {

    public static void main(String[] args) {
        ActionListener listener = new CurrentTimePrinter();

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

您需要在 non-daemon thread 上执行您的代码。当前发生的情况是 Timer 作为守护线程启动,但作为 main returns JVM 退出。

您可以像这样从 EDT(非守护程序)启动计时器:

public static void main(String[] args) {

    ActionListener listener = new CurrentTimePrinter();
    SwingUtilities.invokeLater(() -> new Timer(1000, listener).start());
}

这使 JVM 保持活动状态。

关于线程的一些额外注意事项:

swing.Timer 是一个简化的 class,为与 GUI 一起使用而定制。随之而来的是灵活性较低的缺点。所有此类计时器 运行 都设置在后台并且是守护进程的线程。

util.Timer has by default a non-daemon thread and has the flexibility to be created otherwise。每个计时器都有自己的线程。