首页 文章

JavaFX异常关闭警报返回不正确的结果

提问于
浏览
2

我创建了一个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");
    }

}

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

是否或已关闭

但是,我实际看到的是:

是的

Dialog documentation声明"abnormal closing condition"(例如单击右上角的小"x")将"attempt to set the result property to whatever value is returned from calling the result converter with the first matching ButtonType."鉴于此语句的上下文,我将"matching ButtonType"解释为一个ButtonType(从文档中直接引用):

该按钮具有ButtonType,其ButtonBar.ButtonData的类型为ButtonBar.ButtonData.CANCEL_CLOSE . 该按钮具有ButtonType,当调用ButtonBar.ButtonData.isCancelButton()时,ButtonBar.ButtonData返回true .

我对文档的解释是否不正确,或者这是JavaFX中的错误?无论为什么这不能按照我的预期工作,在这种情况下,有什么方法可以强制"abnormal closing conditions"返回 ButtonType.NO

1 回答

  • 1

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

    setOnShowing(event -> setResult(null));
    

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

相关问题