为什么这段代码会循环? (ActionListener的概念)

时间:2013-10-13 00:09:45

标签: java swing actionlistener

我对此有点失落。所以这里有一些ActionListener的代码:

public static void main(String[] args)
  {

    ActionListener listener = new ActionListener(){

      public void actionPerformed(ActionEvent event){
        System.out.println("hello");

      }
    };
    Timer displayTimer = new Timer(5000, listener);
    displayTimer.start();


  }

它一遍又一遍地打印你好......我不太明白。为什么不打印一次?

感谢

2 个答案:

答案 0 :(得分:2)

因为你使用的是Timer而没有调用displayTimer.setRepeats(false);

但是,我建议使用ExecutorService代替Timer。见this question。 Java中缺少Timer的一些内容,请参阅this question,这也可以帮助您设置一个ExecutorService,其行为就像您习惯的Timer一样。

答案 1 :(得分:1)

正如(计时器)[http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html]的文档所说,你的构造函数初始化了初始延迟和事件间延迟五秒钟。因此,计时器每五秒执行一次ActionListener。