我是Java初学者,在我的游戏JavaFX控制器中,我有以下代码片段。它是一个按钮,可以激活一个每5秒做一次的定时器,它完全正常工作:
double seconds = 5.0;
@FXML
void unlockBtn(ActionEvent event) {
Timeline timer = new Timeline(new KeyFrame(Duration.seconds(seconds), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("this is called every"+seconds+"seconds on UI thread");
}
}));
timer.setCycleCount(Timeline.INDEFINITE);
timer.play();
}
然后我还有一个按钮可以改变&#34;秒&#34;变量,它的代码如下所示:
@FXML
void upgradeSecondsBtn(ActionEvent event) {
seconds = 2.0;
}
它应该做什么:它应该更新计时器,使它现在执行2秒而不是5秒的事情。显然,这不起作用。
如何在单击按钮时更改定时器的速率?
答案 0 :(得分:0)
这样的事情应该有效
Timeline timer;
@FXML
void unlockBtn(ActionEvent event) {
createTimer(5.0);
}
private void createTimer(double seconds) {
if (timer != null) {
timer.stop();
}
timer = new Timeline(new KeyFrame(Duration.seconds(seconds), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("this is called every"+seconds+"seconds on UI thread");
}
}));
timer.setCycleCount(Timeline.INDEFINITE);
timer.play();
}
@FXML
void upgradeSecondsBtn(ActionEvent event) {
createTimer(2.0);
}