【发布时间】:2015-06-10 11:45:46
【问题描述】:
我有一个 JavaFx 应用程序,我在其中显示一个警告框,使用:
alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Title");
alert.setHeaderText("Some Text");
alert.setContentText("Choose your option.");
buttonTypeOne = new ButtonType("Yes");
buttonTypeCancel = new ButtonType("No", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeCancel);
Optional<ButtonType> result = alert.showAndWait();
因为警报执行showAndWait,所以它会一直显示,直到用户按下“是”或“否”或“关闭”对话框。
问题:我需要从其他地方以编程方式关闭此对话框。详细说明一下,假设用户在 20 秒内没有选择任何选项,或者假设此警报框显示为某个刚刚结束的后台进程,现在我希望通过将 result 设置为来关闭此警报框是buttonTypeCancel,而不是用户按下任何按钮。
(就像 Swing 中的 dispose 方法)
我该怎么做?我尝试了 Event.fireevent (https://stackoverflow.com/a/22459308/3155986),但我无法编写正确的关联事件。
提前致谢!
编辑:包括示例代码-
- MainApp.java - 负责处理应用程序的 Java 类
- Controller.java - 对应的控制器文件
- Design.fxml - 通过 MainApp.java 加载并由 Controller.java 控制的应用程序的 FXML 文件
-
Compute.java - 另一个执行计算的 java 类。
公共类计算{ 警报警报;
public void function1{ Platform.runLater(new Runnable(){ public void run(){ alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Title"); alert.setHeaderText("Some Text"); alert.setContentText("Choose your option."); buttonTypeOne = new ButtonType("Yes"); buttonTypeCancel = new ButtonType("No", ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeCancel); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeOne){ // ... user chose "One" } else { // ... user chose CANCEL or closed the dialog } } }); } public void function2{ //......Does some long computation here //.... If the computation finishes before the user chooses 'Yes' or 'No' on alert box //...Then close the alertbox here and execute the code corresponding to buttonTypeCancel //..I tried alert.close(); and alert.hide(); but doesn't work. }}
另外,是否有任何替代解决方案可以做到这一点?最初,我想保持Compute.java 中没有任何 javafx 代码,但不知道怎么做。
【问题讨论】:
-
如果你有引用
Window(Stage)或Alert(Dialog),你可以同时调用它们的.close()。 -
我为警报框尝试了 .close()/ .hide(),但它没有执行。当警报框从javacode的其他地方被强制关闭时,我希望执行
buttonTypeCancel的代码。