当用户尝试退出应用程序时显示确认对话框(按 X 按钮)

问题描述 投票:0回答:3

我想修改 javafx 应用程序中的默认退出过程,以向用户显示确认对话框。如果用户选择“确定”,确认对话框将退出应用程序;如果用户选择“取消”,确认对话框将保持应用程序运行。

我应该怎么做才能在javaFX中实现这个?

java javafx javafx-8
3个回答
2
投票

从 8.40 起您可以使用警报

stage.setOnCloseRequest(evt -> {
    Alert alert = new Alert(AlertType.CONFIRMATION);
    alert.setTitle("Confirm Close");
    alert.setHeaderText("Close program?");
    alert.showAndWait().filter(r -> r != ButtonType.OK).ifPresent(r->evt.consume());
});

1
投票
primaryStage.addEventFilter(WindowEvent.WINDOW_CLOSE_REQUEST, e->{
    e.consume();
    Popup popup = new Popup();
    HBox buttons = new HBox();
    Button close = new Button("close");
    Button cancel = new Button("cancel");
    buttons.getChildren().addAll(close,cancel);
    buttons.setPadding(new Insets(5,5,5,5));
    popup.getContent().add(buttons);
    popup.show(primaryStage);
    close.setOnAction(ex -> {
        Platform.exit();
    });
    cancel.setOnAction(ec -> {
        popup.hide();
    });
});

0
投票

我遵循了这种方法...

创建舞台后,我使用此代码启动弹出窗口并退出...

stage.setOnCloseRequest((WindowEvent arg0) -> {
        arg0.consume();
        Alert exitAlert = new Alert(AlertType.CONFIRMATION);
        exitAlert.setTitle("Exit Confirmation");
        exitAlert.setHeaderText(null);
        exitAlert.setContentText("Do you really need to exit ?");

        ButtonType yesBtn = new ButtonType("Yes", ButtonData.YES);
        ButtonType noBtn = new ButtonType("No", ButtonData.NO);

        exitAlert.getButtonTypes().setAll(yesBtn, noBtn);
        exitAlert.initOwner(getScene().getWindow());
        exitAlert.showAndWait();
        if (exitAlert.getResult().getButtonData() == ButtonData.YES) {
            Platform.exit();
            System.exit(0);
        }
    });
© www.soinside.com 2019 - 2024. All rights reserved.