0

I'm a bit lost on this. So here's some code for an 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();


  }

And it prints hello over and over... I don't quite understand. why doesn't it just print once?

thanks

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Caffeinated
  • 11,982
  • 40
  • 122
  • 216

2 Answers2

2

Because you are using a Timer and haven't called displayTimer.setRepeats(false);

However, I recommend using a ExecutorService instead of Timer. See this question. There are a few things that a Timer in Java is lacking, see this question which will also help you setup an ExecutorService that will behave just like a Timer that you are used to.

Community
  • 1
  • 1
Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
1

As the documentation to (Timer)[http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html] says, your constructor initializes the timer with both an initial delay and a between-event delay of five seconds. The timer thus executes your ActionListener every five seconds.

Joey
  • 344,408
  • 85
  • 689
  • 683