JavaFX 异常关闭警报返回错误结果

标签 java javafx dialog modal-dialog javafx-8

我创建了一个 JavaFX Alert 对象,它在调用 showAndWait 时返回意外结果。下面的代码说明了我观察到的行为:

package myPackage;

import java.util.Optional;

import javafx.application.Application;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(final String[] args) {
        launch();
    }

    private static boolean isYes(final Optional<ButtonType> result) {
        return (result.isPresent() && result.get().getButtonData() == ButtonData.YES);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        final Alert alert = new Alert(AlertType.CONFIRMATION,
            "This is a test", ButtonType.NO, ButtonType.YES);
        System.out.println(isYes(alert.showAndWait()) ? "Yes" : "No or Closed");
        System.out.println(isYes(alert.showAndWait()) ? "Yes" : "No or Closed");
    }

}

当我运行上面的应用程序时,会显示两个对话框。在第一个对话框中单击"is",然后关闭(通过单击右上角的“x”)第二个。通过执行上述步骤,我希望应用程序打印以下内容:

Yes
No or Closed

但是,我实际看到的打印内容是:

Yes
Yes

Dialog documentation指出“异常关闭条件”(例如单击右上角的小“x”)将“尝试将结果属性设置为使用第一个匹配的 ButtonType 调用结果转换器返回的任何值。”鉴于此声明的上下文,我将“匹配的 ButtonType”解释为表示一个 ButtonType(直接引用自文档):

  1. The button has a ButtonType whose ButtonBar.ButtonData is of type ButtonBar.ButtonData.CANCEL_CLOSE.
  2. The button has a ButtonType whose ButtonBar.ButtonData returns true when ButtonBar.ButtonData.isCancelButton() is called.

是我对文档的解释不正确,还是 JavaFX 中的错误?不管为什么这不像我预期的那样工作,在这种情况下,有什么方法可以强制“异常关闭条件”返回 ButtonType.NO 吗?

最佳答案

这是 JavaFX 中的另一个错误。我已将其报告给 Oracle,并为其分配了 Bug ID JDK-8173114 .作为变通方法,我只是将以下行添加到我的 JavaFX Alert 子类的构造函数中:

setOnShowing(event -> setResult(null));

上述解决方法似乎适用于 AlertChoiceDialogTextInputDialog

关于JavaFX 异常关闭警报返回错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41603504/

相关文章:

java - 通过浏览器显示或下载图像

java - Google Drive API - 如何使用域范围服务帐户并从域获取所有文档列表

java - 用 jar 打开时图像不可见。升级 javaFx 后创建新图像需要完整目录

css - 如何在运行时为 javaFX ProgressBar 设置特定的 css 值?

java - 在 Swing JFrame 上添加 WebView 控件

.NET:如何让 Escape 关闭 MessageBox.Show()?

java - JNDI 无法在 Tomcat 6 上创建 JDBC 连接

java - android Horizo​​ntalScrollView 中左右滚动的按钮

java - 正面点击时 Android 对话框崩溃

javascript - 如何按 Enter 键关闭此 AngularJS 对话框通知框?