如何在 Java 应用程序的方法中禁止按键?

How to prohibit Key Press during a method in Java application?

我正在使用 JavaFX 和 Scene Builder 制作应用程序。我有一种制作锚窗格动画的方法。平移过渡和旋转过渡。

当我在键盘上按下“1”时调用该方法。

The problem is when I press on key 1 so fast animation works incorrectly. It seems when I press too fast on a key animation of Anchor Pane is shifted.

如何在动画期间禁止按键或如何设置按键之间的延迟?

控制器:

@FXML  private AnchorPane randomCard;

@FXML public void initialize(URL location, ResourceBundle resources) {    

//key commands
mainAnchor.setOnKeyPressed(event -> {
  switch (event.getCode()) {       
    case DIGIT1:          
      showRandomCard();
      break;
  }
});

//show random card in main window
 private void showRandomCard(){

    TranslateTransition tt = new TranslateTransition();
    tt.setDuration(Duration.millis(400));
    tt.setNode(randomCard);
    tt.setFromY(950);
    tt.setFromX(-600);
    tt.setToY(0);
    tt.setToX(0);        

    RotateTransition rt = new RotateTransition(Duration.millis(500), randomCard);
    rt.setByAngle(360);
    rt.setRate(1);
    rt.setCycleCount(1);        

    tt.play();       
    rt.play();

 }

只需使用 boolean 字段并使用最后完成的动画的 onFinished 处理程序将其重置为允许执行 creating/starting 动画逻辑的状态:

private boolean animationRunning = false;
private void showRandomCard(){
    if (!animationRunning) {
        animationRunning = true;
        TranslateTransition tt = new TranslateTransition();
        tt.setDuration(Duration.millis(400));
        tt.setNode(randomCard);
        tt.setFromY(950);
        tt.setFromX(-600);
        tt.setToY(0);
        tt.setToX(0);

        RotateTransition rt = new RotateTransition(Duration.millis(500), randomCard);
        rt.setByAngle(360);
        rt.setRate(1);
        rt.setCycleCount(1);
        rt.setOnFinished(evt -> animationRunning = false);

        tt.play();
        rt.play();
    }

}