4

现在,我的代码看起来像这样:

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

根据我所看到的(以及该类的JavadocsTimer),计时器将等待 5000 毫秒(5 秒),触发动作事件,等待 5000 毫秒,再次触发,依此类推。但是,我试图获得的行为是启动计时器,触发事件,计时器等待 5000 毫秒,再次触发,然后在再次触发之前等待。

除非我错过了什么,否则我看不出有一种方法可以创建一个在触发前不等待的计时器。有没有一种好的、干净的方法来模仿这个?

4

4 回答 4

10

您只能在构造函数中指定延迟。您需要更改初始延迟(触发第一个事件之前的时间)。不能在构造函数中设置,但可以使用 Timer 类的setInitialDelay方法。

如果您在第一次射击前无需等待:

timer.setInitialDelay(0);
于 2009-09-16T12:52:40.030 回答
2

我不确定这是否会有很大帮助,但是:

Timer timer = new javax.swing.Timer(5000, myActionEvent){{setInitialDelay( 0 );}};
于 2009-09-16T17:15:16.697 回答
0

我根本不会使用 Timer,而是使用ScheduledExecutorService

import java.util.concurrent.*

...

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

请注意,therescheduleAtFixedRate()scheduleWithFixedDelay()which 的语义略有不同。阅读 JavaDoc 并找出您需要哪一个。

于 2009-09-16T12:56:37.103 回答
0

简单的解决方案:

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

但我更喜欢。timer.setInitialDelay(0)

于 2009-09-16T13:27:31.283 回答