警报类型 none 关闭 javafx

alert type none closing javafx

我有一个带有菜单栏的程序,其中有一个 'About' 按钮来显示有关该应用程序的一些信息。

问题是,当我使用 AlertType.INFORMATION 时,我可以点击确定按钮关闭警报,但是当我使用 NONE 时,当我点击关闭 window 按钮时,没有任何反应.我已经尝试放置一个 setOnCloseAction(e-> close());但它也没有关闭。

谢谢!

public class RootLayoutController {

private MainApp main;

@FXML
private MenuItem loadFiles;

@FXML
private MenuItem about;

@FXML
private void displayAbout() {
    Alert alert = new Alert(AlertType.NONE);
    alert.initStyle(StageStyle.UTILITY);
    alert.initOwner(main.getPrimaryStage());
    alert.setTitle("Organiz3r");
    alert.setHeaderText("Organiz3r v1.0");
    alert.setContentText("Developed at BitBucket");
    alert.showAndWait();
}

@FXML
private void handleLoad() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Open Files");
    List<File> files = fileChooser.showOpenMultipleDialog(main.getPrimaryStage());
    main.loadFiles(files);
}

public RootLayoutController() {
    // TODO Auto-generated constructor stub
}

public void setMain(MainApp main) {
    this.main = main;
}

主设置为 class 主

// Load root layout from fxml file.
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainApp.class.getResource("view/RootLayout.fxml"));
        rootLayout = (BorderPane) loader.load();

        RootLayoutController controller = loader.getController();
        controller.setMain(this);

documentation 解释(在 "Dialog Closing Rules" 部分)按下 window 关闭按钮将无效,除非只有一个按钮,或者有两个或更多按钮按钮,其中一个本质上是一个 "Cancel" 按钮。因此,当您使用 AlertType.NONE 创建 Alert 时,它没有按钮,因此使用标准 "window close" 按钮关闭它时将被忽略。

因此,如果您不想要AlertType.INFORMATION,您需要在您的提醒中添加一个按钮,您可以使用

alert.getDialogPane().getButtonTypes().add(ButtonType.OK);

根据 Dialog documentation 看来您必须在 Dialog/Alert 中至少有一个按钮才能使用角落的“x”按钮关闭它。根据文档,使用“x”按钮关闭被认为是“异常”关闭。内容如下:

JavaFX dialogs can only be closed 'abnormally' (as defined above) in two situations:

When the dialog only has one button, or

When the dialog has multiple buttons, as long as one of them meets one of the following requirements:

The button has a ButtonType whose ButtonBar.ButtonData is of type ButtonBar.ButtonData.CANCEL_CLOSE.

The button has a ButtonType whose ButtonBar.ButtonData returns true when ButtonBar.ButtonData.isCancelButton() is called. In all other situations, the dialog will refuse to respond to all close requests...

您可以使用 AlertType.INFORMATION 然后隐藏 'OK' 按钮。这使您可以使用角落的 'x' 按钮关闭 window,而无需其他按钮。

dialogPane.lookupButton(ButtonType.OK).setVisible(false);