【发布时间】:2018-10-08 14:29:49
【问题描述】:
我在看这个问题JavaFX show dialogue after thread task is completed,但我的问题恰恰相反。在需要用户返回一些数据的文件选择器或警报之后,最好的方法是什么?
这是我现在拥有的:
Platform.runLater(()->{
File file = fileChooser.showOpenDialog(root.getScene().getWindow());
if(file == null) {
return;
}
executorService.execute(()->{
//more code here which uses file
});
});
其中 executorService 是之前创建的 ExecutorService。我想我可以很容易地使用 Task 或 Thread 或其他任何东西,但是它的线程化方式并不重要,只是这需要一段时间,我不想在 Application 线程上发生,因为它会锁定用户界面。
我知道这不是 mvce,但我希望它能够证明我在 Platform.runLater 调用中遇到的线程问题。
这是一个极端的例子,说明这种事情变得多么复杂
@FXML
public void copyFiles(ActionEvent event){
//this method is on the application thread because a button or something started it
// so we thread off here
executorService.execute(()->{
// do some stuff
// ...
// get location to copy to from user
// must happen on the application thread!
Platform.runLater(()->{
File file = fileChooser.showOpenDialog(root.getScene().getWindow());
if(file == null) {
return;
}
executorService.execute(()->{
// more code here which uses file
// ...
// oh wait, some files have the same names!
// we need a user's confirmation before proceeding
Platform.runLater(()->{
Alert alert = new Alert(AlertType.CONFIRMATION, "Do you want to overwrite files with the same names?", ButtonType.OK, ButtonType.CANCEL);
Optional<ButtonType> choice = alert.showAndWait();
if(choice.isPresent && choice.get == ButtonType.OK){
// do something, but not on the application thread
executorService.execute(()->{
// do the last of the copying
// ...
});
}
});
});
});
});
}
【问题讨论】:
标签: java multithreading javafx