javafx 8 dialog and concurrency

2019-07-12 13:25发布

问题:

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