定时器没有启动?

时间:2015-11-11 17:25:40

标签: java swing timer

我一直在displayTimer.start()中遇到预期的错误;线......这是什么原因?我只是想了解如何使用带有两个输入的swing计时器进入构造函数,而没有其他更高级的东西。我从以下代码获得了此代码:http://albertattard.blogspot.com/2008/09/practical-example-of-swing-timer.html

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

public class Five {
    public static void main(String[] args){
        ActionListener listener = new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    System.out.println("hello");
                }
            };
        Timer displayTimer = new Timer(1000, listener);
        displayTimer.start();
    }
}

1 个答案:

答案 0 :(得分:2)

  

添加修复该错误的主要方法,但现在它似乎不会一直在运行......它永远不会打印你好。

可能是因为在Timer有机会触发之前JVM存在。 Timer的目的是将它与GUI一起使用。

因此,创建一个更实际的例子。首先创建一个JFrame并使框架可见。然后,当框架可见时,JVM不会退出。然后你可以启动Timer。

阅读Concurrency上Swing教程中的部分,了解有关Swing中使用的不同线程的更多信息。