簡體   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();
      }
}

我正在嘗試制作一個計時器,該計時器每秒鍾輸出一個單詞hello,但是當我鍵入DELAY值1000時,它會輸出一次hello,然后終止。 我究竟做錯了什么 ? 所有幫助表示贊賞!

在計時器觸發之前,JVM已退出。

嘗試:

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

看看區別。

或者更好的方法是在事件調度線程(EDT)上執行代碼。 所有GUI代碼都應在EDT上執行。 通過使用SwingUtitities.invokeLater(),可以確保在執行代碼時創建了EDT:

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

閱讀Swing 並發教程中有關EDT的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM