当我执行计时器时,我尝试用RaffleImage();使图像闪烁,我的角色对任何碰撞免疫,我希望它只免疫2秒,所以计时器只执行2秒,然后就完成了。
我试着减去System.currentTimeMillis(),但我用这种方法创建的任何变量都具有相同的值,这使得我从减法中得到一个零。
你知道如何停止或暂停计时器在任何经过的时间后,以秒为单位?
immuneTimer = new Timer(50, new ActionListener() {
@Override
public synchronized void actionPerformed(ActionEvent e) {
long initMillis = System.currentTimeMillis();
if (System.currentTimeMillis() - initMillis > 2000 ) { // this substract gives me 0
initImages();
setImmune(false); // so this never reached
immuneTimer.stop();
} else {
raffleImage(); //its executing like forever;
}
}
});发布于 2019-06-24 04:59:22
Swing计时器触发一个ActionEvent。从事件中,您可以使用getSource()来获取事件的源代码。将该源代码转换为swing timer object并使用它将其关闭。
要知道何时关闭它,您需要有一个变量count,该变量表示调用swing计时器的次数。当变量达到该数量时,将其关闭。
int elapsedTime = 0;
int timerDelay = 50;
int max = 2000;
public void actionPerformed(ActionEvent ae) {
elapsedTime += timerDelay; // you could use getDelay here but it
// is in milliseconds.
if (elapsedTime >= max) {
Timer s = (Timer)ae.getSource();
s.stop();
}
// rest of code
}https://stackoverflow.com/questions/56727645
复制相似问题