I am calling a method inside my UI thread. Inside this method a new thread is created. I need the UI thread to wait until this new thread is finished because I need the results of this thread to continue the method in the UI thread. But I don´t want to have UI frozen while its waiting. Is there some way to make the UI thread wait without busy waiting?.
You should never make the FX Application Thread wait; it will freeze the UI and make it unresponsive, both in terms of processing user action and in terms of rendering anything to the screen.
If you are looking to update the UI when the long running process has completed, use the javafx.concurrent.Task
API. E.g.
someButton.setOnAction( event -> {
Task<SomeKindOfResult> task = new Task<SomeKindOfResult>() {
@Override
public SomeKindOfResult call() {
// process long-running computation, data retrieval, etc...
SomeKindOfResult result = ... ; // result of computation
return result ;
}
};
task.setOnSucceeded(e -> {
SomeKindOfResult result = task.getValue();
// update UI with result
});
new Thread(task).start();
});
Obviously replace SomeKindOfResult
with whatever data type represents the result of your long-running process.
Note that the code in the onSucceeded
block:
task.getValue()
Hence this solution can do anything you could do by "waiting for the task to finish", but doesn't block the UI thread in the meantime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With