How to make a text field editable within 10 seconds with the click of a button?

Using JavaFX, with the click of a button I want to do this:

spinBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
    field.setDisable(false);
    //Delay for 10 seconds
    field.setDisable(true);         
    }
});

I quickly realized that sleep would not work, as it completely freezes the GUI. I also tried sleeping threads to get a timer, but which still depends on the GUI if the input signal is where I want a delay. (Example below)

spinBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
    ExampleTimerThread exampleSleepyThread = new ExampleTimerThread();//this extends Thread
    exampleSleepyThread.start(); 
//thread sleeps for 10 secs & sets public static boolean finished = true; after sleep 
    while(finished == true){
        field.setDisable(false);
        }           
    }
});

What can I do to prevent this code from freezing the GUI? I know in Swing, there is a timer. Is there something similar in JavaFX?

+4
source share
1 answer

Use PauseTransitionto delay events:

spinBtn.setOnAction(e -> {
    field.setDisabled(false);
    PauseTransition pt = new PauseTransition(Duration.seconds(10));
    pt.setOnFinished(ev -> {
        field.setDisabled(true);
    });
    pt.play();
});
+8
source

Source: https://habr.com/ru/post/1690225/


All Articles