JAVAFX:如何在特定时间禁用按钮?

Roh*_*han 5 javafx-2

我想在JavaFX应用程序中禁用特定时间的按钮.有没有选择这样做?如果没有,是否有任何解决方法?

以下是我的应用程序代码.我试过Thread.sleep,但我知道这不是阻止用户点击下一个按钮的好方法.

nextButton.setDisable(true);
final Timeline animation = new Timeline(
        new KeyFrame(Duration.seconds(delayTime),
        new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                nextButton.setDisable(false);
            }
        }));
animation.setCycleCount(1);
animation.play();
Run Code Online (Sandbox Code Playgroud)

Mic*_*rry 5

您可以使用提供相关GUI调用的线程的简单方法(runLater()当然):

new Thread() {
    public void run() {
        Platform.runLater(new Runnable() {
            public void run() {
                myButton.setDisable(true);
            }
        }
        try {
            Thread.sleep(5000); //5 seconds, obviously replace with your chosen time
        }
        catch(InterruptedException ex) {
        }
        Platform.runLater(new Runnable() {
            public void run() {
                myButton.setDisable(false);
            }
        }
    }
}.start();
Run Code Online (Sandbox Code Playgroud)

它可能不是实现它的最佳方式,但可以安全地工作.


Ulu*_*Biy 5

您还可以使用Timeline

  final Button myButton = new Button("Wait for " + delayTime + " seconds.");
  myButton.setDisable(true);

  final Timeline animation = new Timeline(
            new KeyFrame(Duration.seconds(delayTime),
            new EventHandler<ActionEvent>() {
                @Override public void handle(ActionEvent actionEvent) {
                    myButton.setDisable(false);
                }
            }));
  animation.setCycleCount(1);
  animation.play();
Run Code Online (Sandbox Code Playgroud)