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

时间:2013-06-04 13:54:10

标签: 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();

4 个答案:

答案 0 :(得分: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();

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

答案 1 :(得分:4)

您也可以使用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();

答案 2 :(得分:2)

禁用JavaFX控件的方法是:

myButton.setDisable(true);

您可以以任何方式以编程方式实现时间逻辑,方法是轮询计时器或调用此方法以响应某些事件。

如果您已经在SceneBuilder中通过FXML创建了此按钮实例,那么您应该为按钮指定一个fx:id,以便在加载场景图期间将其引用自动注入控制器对象。这将使您更容易在控制器代码中使用。

如果您以编程方式创建了此按钮,那么您的代码中已经有了它的参考。

答案 3 :(得分:0)

或者您可以使用服务并将运行属性绑定到要禁用的按钮的disableProperty。

public void start(Stage stage) throws Exception {
    VBox vbox = new VBox(10.0);
    vbox.setAlignment(Pos.CENTER);      

    final Button button = new Button("Your Button Name");
    button.setOnAction(new EventHandler<ActionEvent>() {            
        @Override
        public void handle(ActionEvent event) {
            Service<Void> service = new Service<Void>() {                   
                @Override
                protected Task<Void> createTask() {
                    return new Task<Void>() {
                        @Override
                        protected Void call() throws Exception {
                            Thread.sleep(5000);//Waiting time
                            return null;
                        }
                    };
                }
            };
            button.disableProperty().bind(service.runningProperty());               
            service.start();
        }
    });     

    vbox.getChildren().addAll(button);
    Scene scene = new Scene(vbox, 300, 300);
    stage.setScene(scene);
    stage.show();
}

但是Uluk Biy给出的时间线解决方案看起来更优雅。