javafx 8 dialog and concurrency

☆樱花仙子☆ 提交于 2019-12-12 16:37:32

问题


I want to show a custom JavaFX 8 dialog to a user, capture data from the user and then close the dialog after the data is saved to the database (or shows an error message\alert).

At the moment, the dialog is shown with the following code:

Optional<MyType> result = dialog.showAndWait();

Followed by code:

myrepository.save(result)

From reading the documentation, it looks like instead I should perform this repository.save in a background Task?

It looks like this code could only be executed after showAndWait(); and couldn't close the standard dialog as this would need to be done on the JavaFX application thread?

Is there a way to only show the dialog, save the data, and then show a confirmation dialog only if the database save succeeds on the background Task?


回答1:


From reading the documentation, it looks like i should perform this repository.save in a background Task?

Yes, it is correct because database queries take time and we don't want our application to become unresponsive while the database query is executed. Running tasks on the background thread avoids it.

Is there a way to only close the dialog and show a confirmation dialog if the database save succeeds on the background Task?

You can use task's succeeded property to close the previous dialog and open a new one.

// If database query is successful
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
    @Override
    public void handle(WorkerStateEvent t) {
        // Code to close the previous dialog
        //Show confirmation dialog
    }
});

Similarly, if the task fails you can use the failed property to update the dialog or show a new dialog.

// On fail
// Using Lambda
runFactoryTask.setOnFailed( t -> {
    // Update 
});

There is a very nice answer by James_D on using threads and database, I strongly recommend to go through it :

  • Using threads to make database requests


来源:https://stackoverflow.com/questions/33658082/javafx-8-dialog-and-concurrency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!