JavaFX: How to disable a button for a specific amount of time?

后端 未结 4 1087
轻奢々
轻奢々 2021-01-13 10:48

I want to disable a button for a specific time in JavaFX application. Is there any option to do this? If not, is there any work around for this?

Below is my code in

4条回答
  •  星月不相逢
    2021-01-13 11:17

    Or you could use a Service and bind the running property to the disableProperty of the button do you want to disable.

    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() {            
            @Override
            public void handle(ActionEvent event) {
                Service service = new Service() {                   
                    @Override
                    protected Task createTask() {
                        return new Task() {
                            @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();
    }
    

    But the Timeline solution given by Uluk Biy, looks more elegant.

提交回复
热议问题