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 . Eg
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.
Just call a method that notifies the GUI when the Thread is finished. Something like this:
class GUI{
public void buttonPressed(){
new MyThread().start();
}
public void notifyGui(){
//thread has finished!
//update the GUI on the Application Thread
Platform.runLater(updateGuiRunnable)
}
class MyThread extends Thread{
public void run(){
//long-running task
notifyGui();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.