你如何创建一个立即触发的javax.swing.Timer,然后每隔t毫秒?
现在,我的代码看起来像这样:
Timer timer = new javax.swing.Timer(5000, myActionEvent);
根据我所看到的(以及Timer
类的Javadoc ),计时器将等待5000毫秒(5秒),触发动作事件,等待5000毫秒,再次触发,依此类推。 但是,我试图获得的行为是计时器启动,事件被触发,计时器等待5000毫秒,再次触发,然后等待再次触发。
除非我错过了什么,否则我没有办法创建一个在开火前不等待的计时器。 是否有一种良好,干净的方式来模仿这个?
您只能在构造函数中指定延迟。 您需要更改初始延迟(触发第一个事件之前的时间)。 您不能在constuctor中设置,但可以使用Timer类的setInitialDelay方法。
如果你在第一次射击前不需要等待:
timer.setInitialDelay(0);
我不确定这是否会有很大帮助,但是:
Timer timer = new javax.swing.Timer(5000, myActionEvent){{setInitialDelay( 0 );}};
我根本不会使用Timer,而是使用ScheduledExecutorService
import java.util.concurrent.* ... ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleAtFixedRate(myRunnable, 0, 5, TimeUnit.SECONDS);
请注意, scheduleAtFixedRate()
和scheduleWithFixedDelay()
语义略有不同。 阅读JavaDoc并找出您需要的JavaDoc。
简单解决方案
Timer timer = new javax.swing.Timer(5000, myActionEvent); myActionEvent.actionPerformed(new ActionEvent(timer, 0, null));
但我喜欢timer.
setInitialDelay
(0)
好多了。