Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a textfield editable for 10 seconds on the click of a button?

Using JavaFX, on 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 sleeping wouldn't work as it freezes the GUI completely. I've also tried sleeping threads to get a timer but that still freezes the GUI if input where I want the 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 could I do to prevent this code from freezing the GUI up? I know in Swing, there is a timer. Is there something similar in JavaFX?

like image 425
Lalenci Avatar asked Jan 29 '23 02:01

Lalenci


1 Answers

Use PauseTransition to delay events:

spinBtn.setOnAction(e -> {
    field.setDisabled(false);
    PauseTransition pt = new PauseTransition(Duration.seconds(10));
    pt.setOnFinished(ev -> {
        field.setDisabled(true);
    });
    pt.play();
});
like image 149
MBec Avatar answered Jan 31 '23 17:01

MBec