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

故事扮演 提交于 2019-12-01 19:48:47

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);

I am not sure if this will be of much help, but:

Timer timer = new javax.swing.Timer(5000, myActionEvent){{setInitialDelay( 0 );}};

I wouldn't use a Timer at all, but instead use a ScheduledExecutorService

import java.util.concurrent.*

...

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(myRunnable, 0, 5, TimeUnit.SECONDS);

Please note that there is scheduleAtFixedRate() and scheduleWithFixedDelay() which have slightly different semantics. Read the JavaDoc and find out which one you need.

Simple solution:

Timer timer = new javax.swing.Timer(5000, myActionEvent);
myActionEvent.actionPerformed(new ActionEvent(timer, 0, null));

But I like timer.setInitialDelay(0) a lot better.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!