为什么我的计时器事件在我每次再次启动时开始触发得越来越快?
Why does my timer event start triggering faster and faster every time I start it again?
我正在构建的游戏需要一个计时器,它的基本功能是触发一个事件,当我点击播放时,该事件每秒移动一个正方形。现在我要么让游戏顺其自然(游戏结束或物体移出边界),要么再次按下播放键,计时器似乎触发物体比以前移动得更快,依此类推,每次都越来越快我重新开始时间。
private void playButtonMouseClicked(java.awt.event.MouseEvent evt) {
/*code*/
timer = new Timer(timerSpeed, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
/*code that ends with something that calls timer.stop()*/
}
}
});
if(timer.isRunning()) //in case I don't let the game stop the timer
timer.stop();
timer.start();
}
我检查了timer.getDelay()
,延迟没有改变,保持不变,但我可以看到箭头每次移动得越来越快。我正在使用 jPanels 和带有 和 图标的标签来显示网格和移动对象。
有什么想法吗?
but I can see the arrow moving faster and faster every time.
这告诉我你有多个定时器在执行。
每次单击按钮时,您当前的代码都会创建一个新的计时器。
timer.isRunning()
检查永远不会为真,因为您刚刚创建了一个新的 Timer,它不会 运行 因为您还没有启动它。
因此您的旧 Timer 可能仍然是 运行 但是因为您不再有对它的引用,所以您无法停止它。
解决方法:
不要在每次单击按钮时都创建一个新的 Timer 对象。 Timer 对象应该在 class 的构造函数中创建。然后你只需要start/stop定时器
我正在构建的游戏需要一个计时器,它的基本功能是触发一个事件,当我点击播放时,该事件每秒移动一个正方形。现在我要么让游戏顺其自然(游戏结束或物体移出边界),要么再次按下播放键,计时器似乎触发物体比以前移动得更快,依此类推,每次都越来越快我重新开始时间。
private void playButtonMouseClicked(java.awt.event.MouseEvent evt) {
/*code*/
timer = new Timer(timerSpeed, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
/*code that ends with something that calls timer.stop()*/
}
}
});
if(timer.isRunning()) //in case I don't let the game stop the timer
timer.stop();
timer.start();
}
我检查了timer.getDelay()
,延迟没有改变,保持不变,但我可以看到箭头每次移动得越来越快。我正在使用 jPanels 和带有 和 图标的标签来显示网格和移动对象。
有什么想法吗?
but I can see the arrow moving faster and faster every time.
这告诉我你有多个定时器在执行。
每次单击按钮时,您当前的代码都会创建一个新的计时器。
timer.isRunning()
检查永远不会为真,因为您刚刚创建了一个新的 Timer,它不会 运行 因为您还没有启动它。
因此您的旧 Timer 可能仍然是 运行 但是因为您不再有对它的引用,所以您无法停止它。
解决方法:
不要在每次单击按钮时都创建一个新的 Timer 对象。 Timer 对象应该在 class 的构造函数中创建。然后你只需要start/stop定时器