我正在构建 javaFX 用户界面,并在窗口之间进行用户交互,但我遇到了一个问题,我在任何地方都找不到解决方案......
所以基本上我想打开一个对话框,其中包含可由用户填写的输入,一旦完成,应用程序就会启动包含这些信息的后台任务,并且在任务运行时会显示另一个对话框(加载屏幕)。但 !任务期间可能会发生错误,并且可以捕获异常,如果出现错误,我想在另一个对话框中为用户显示异常消息。
所以,首先我有一个带有输入的对话框:
// Init dialog
Dialog<String> inputDialog = new Dialog<>();
inputDialog.setTitle("Meshes generation parameters");
// Add validation buttons
inputDialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK,
ButtonType.CANCEL);
// Creating content
GridPane gridPane = new GridPane();
TextField width = new TextField("15000");
gridPane.add(new Label("Width (meters)"), 0, 0);
gridPane.add(width, 1, 0);
// Filling dialog
inputDialog.getDialogPane().setContent(gridPane);
// Returning result with OK button
inputDialog.setResultConverter(dialogButton -> {
if (dialogButton == ButtonType.OK) {
return width.getText();
}
return null;
});
// Opens dialog until user close it or validate it.
Optional<String> result = inputDialog.showAndWait();
然后,如果结果被触发,我将创建一个任务:
result.ifPresent(width -> {
// Creates task that will run in background
Task task= new Task() {
@Override
protected Object call() throws Exception {
try {
// Do things with 'width'
} catch (Exception e) {
system.out.println("Exception catched in task !");
// Tried to open dialog from here but it never shows
}
return null;
}
}; // End of task
// Open 'loading screen' dialog until task ends
ProgressDialog dialog = new ProgressDialog(meshesGeneration);
dialog.initStyle(StageStyle.TRANSPARENT);
dialog.setTitle("Please wait.");
dialog.setHeaderText("This may take some time, please wait.");
dialog.initStyle(StageStyle.UTILITY);
// Runs the task
new Thread(task).start();
dialog.showAndWait();
});
一切都运行良好,无论失败还是成功,ProgressDialog 都会显示直到任务完成。我可以在控制台中显示异常已被捕获,但捕获中创建的对话框永远不会显示。
我尝试了不同的事情,例如:
task.setOnFailed(e -> {
system.out.println(task.getException().getMessage()); // Nothing
});
我还尝试在任务本身内部添加状态或异常...
} catch (Exception e) {
system.out.println("Exception caught in task !");
failed();
setException(e);
}
但我似乎什么也没发生...我什至得到了 SUCCEEDED 状态,异常被捕获,并且搜索 task.getException() 时出现 nullPointerException (在 result.ifPresent{ 中调用任务外部的这两行... )!
我对多线程非常菜鸟...我错过了什么吗?任何帮助将不胜感激,谢谢:)
最佳答案
假设您正确打开对话框,代码可以正常工作:
} catch (Exception e) {
System.out.println("Exception caught in task!");
Platform.runLater(() -> {
Alert dialog = new Alert(AlertType.ERROR, "Error", ButtonType.OK);
dialog.show();
});
}
<小时/>
触发 onFailed
处理程序的异常标准方法是退出 call
方法并抛出异常:
} catch (Exception e) {
System.out.println("Exception caught in task!");
throw e;
}
您可以简单地删除 try-catch,而不是重新抛出异常,但这不再允许您将消息打印到任务内的控制台。
task.setOnFailed(evt -> {
System.out.println(task.getException().getMessage());
Alert dialog = new Alert(AlertType.ERROR, "Error", ButtonType.OK);
dialog.show();
});
关于java - 如何在后台任务 javaFX 中捕获的异常中显示对话框中的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53591274/