我想向用户显示自定义 JavaFX 8 对话框,从用户捕获数据,然后在将数据保存到数据库后关闭对话框(或显示错误消息\警报)。
目前,该对话框显示了以下代码:
Optional<MyType> result = dialog.showAndWait();
后面是代码:
myrepository.save(result)
从阅读文档来看,我似乎应该在后台任务中执行此repository.save?
看起来此代码只能在 showAndWait();
之后执行,并且无法关闭标准对话框,因为这需要在 JavaFX 应用程序线程上完成?
有没有办法只在后台任务上数据库保存成功时显示对话框,保存数据,然后显示确认对话框?
最佳答案
From reading the documentation, it looks like i should perform this repository.save in a background Task?
是的,这是正确的,因为数据库查询需要时间,并且我们不希望我们的应用程序在执行数据库查询时变得无响应。在后台线程上运行任务可以避免这种情况。
Is there a way to only close the dialog and show a confirmation dialog if the database save succeeds on the background Task?
您可以使用任务的succeeded
属性来关闭上一个对话框并打开一个新对话框。
// 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
}
});
同样,如果任务失败,您可以使用 failed
属性来更新对话框或显示新对话框。
// On fail
// Using Lambda
runFactoryTask.setOnFailed( t -> {
// Update
});
James_D 有一个非常好的答案关于使用线程和数据库,我强烈建议您仔细阅读:
关于concurrency - javafx 8 对话框和并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33658082/