Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a javax.swing.Timer that fires immediately, then every t milliseconds?

Right now, I have code that looks something like this:

Timer timer = new javax.swing.Timer(5000, myActionEvent);

According to what I'm seeing (and the Javadocs for the Timer class), the timer will wait 5000 milliseconds (5 seconds), fire the action event, wait 5000 milliseconds, fire again, and so on. However, the behavior that I'm trying to obtain is that the timer is started, the event is fired, the timer waits 5000 milliseconds, fires again, then waits before firing again.

Unless I missed something, I don't see a way to create a timer that doesn't wait before firing. Is there a good, clean way to emulate this?

like image 281
Thomas Owens Avatar asked Dec 18 '22 05:12

Thomas Owens


1 Answers

You can only specify the delay in the constructor. You need to change the initial delay (the time before firing the first event). You cannot set in the constuctor, but you can use the setInitialDelay method of the Timer class.

If you need no wait before the first firing:

timer.setInitialDelay(0);
like image 61
asalamon74 Avatar answered May 01 '23 12:05

asalamon74