如何在用户单击按钮时更改计时器的关键帧持续时间?

How do I change the KeyFrame duration of my timer when user clicks a button?

我是 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();
}

然后我还有一个按钮可以更改 "seconds" 变量,它的代码如下所示:

 @FXML
void upgradeSecondsBtn(ActionEvent event) {
                seconds = 2.0;
}

它应该做什么:它应该更新计时器,以便它现在执行所有 2 秒而不是 5 秒。显然,这是行不通的。

如何让它在单击按钮时改变计时器的速率?

像这样的东西应该可以工作

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);
}