javafx 8 对话和并发
javafx 8 dialog and concurrency
我想向用户显示自定义 JavaFX 8 对话框,从用户那里捕获数据,然后在数据保存到数据库后关闭对话框(或显示错误 message\alert)。
此时,对话框显示以下代码:
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 关于使用线程和数据库的回答非常好,我强烈建议阅读它:
我想向用户显示自定义 JavaFX 8 对话框,从用户那里捕获数据,然后在数据保存到数据库后关闭对话框(或显示错误 message\alert)。
此时,对话框显示以下代码:
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 关于使用线程和数据库的回答非常好,我强烈建议阅读它: