简体   繁体   English

为什么我的计时器不工作?

[英]Why isn't my timer working?

public class TimerProgram extends JFrame {
    public TimerProgram(){

       int  DELAY=1000;
       Timer t = new Timer(DELAY,new TimerListener());
          t.start();

    }
      class TimerListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            System.out.println("Hello");

          }
        }     

      public static void main(String[]args){
          new TimerProgram();
      }
}

I am trying to make a timer that outputs every second the word hello, but it seems that when I type as the DELAY value 1000 , it outputs hello once and then it terminates. 我正在尝试制作一个计时器,该计时器每秒钟输出一个单词hello,但是当我键入DELAY值1000时,它会输出一次hello,然后终止。 What am I doing wrong ? 我究竟做错了什么 ? All help appreciated! 所有帮助表示赞赏!

The JVM exited before the Timer fired. 在计时器触发之前,JVM已退出。

Try: 尝试:

t.setInitialDelay(0);
t.start();

to see the difference. 看看区别。

Or a better approach is to execute the code on the Event Dispatch Thread (EDT). 或者更好的方法是在事件调度线程(EDT)上执行代码。 All GUI code should execute on the EDT. 所有GUI代码都应在EDT上执行。 By using SwingUtitities.invokeLater() you ensure the EDT has been created when your code executes: 通过使用SwingUtitities.invokeLater(),可以确保在执行代码时创建了EDT:

EventQueue.invokeLater(new Runnable()
{
    public void run()
    {
          new TimerProgram();
    }
});

Read the section from the Swing tutorial on Concurrency for more information about the EDT. 阅读Swing 并发教程中有关EDT的更多信息。

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

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