javafx 8对话框和并发 [英] javafx 8 dialog and concurrency

查看:446
本文介绍了javafx 8对话框和并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向用户显示一个自定义JavaFX 8对话框,从用户捕获数据,然后在数据保存到数据库后关闭对话框(或显示错误消息\alert)。

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();

后跟代码:

myrepository.save(result)

而是我应该在后台任务执行此repository.save?

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

看起来这个代码只能在 showAndWait(); 后执行,并且无法关闭标准对话框因为这将需要在JavaFX应用程序线程上完成?

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?

推荐答案


应该在后台任务中执行此repository.save?

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?

您可以使用任务的 succeeded 属性以关闭上一个对话框并打开新的一个。

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
    }
});



< oracle.com/javase/8/javafx/api/javafx/concurrent/Task.html#failed--rel =nofollow> 失败的 属性更新对话框或显示新对话框。

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 
});

James_D 关于使用线程和数据库,我强烈建议通过它:

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


  • a href =http://stackoverflow.com/questions/30249493/using-threads-to-make-database-requests/30250308#30250308>使用主题发出数据库请求

  • Using threads to make database requests

这篇关于javafx 8对话框和并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆