首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在用户从javafx的对话框中选择一个选项之前,如何防止primaryStage关闭?

在用户从JavaFX的对话框中选择一个选项之前,可以通过以下方法防止primaryStage关闭:

  1. 使用模态对话框:使用JavaFX提供的模态对话框,例如Alert对话框,可以阻止用户与primaryStage进行交互,直到对话框关闭。这样可以确保primaryStage不会在用户选择选项之前关闭。你可以使用Alert类的showAndWait()方法显示对话框,该方法会阻塞主线程,直到对话框关闭。
代码语言:txt
复制
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Confirmation Dialog");
alert.setHeaderText("Are you sure?");
alert.setContentText("Do you want to proceed?");

Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent() && result.get() == ButtonType.OK) {
    // 用户选择了确定按钮
    // 执行相应的操作
} else {
    // 用户选择了取消按钮或关闭对话框
    // 可以选择不执行任何操作或者执行相应的取消操作
}
  1. 自定义对话框关闭事件:如果你使用自定义的对话框,可以通过设置关闭按钮的事件处理程序来防止primaryStage关闭。在关闭事件处理程序中,你可以检查用户选择的选项,并决定是否关闭primaryStage。
代码语言:txt
复制
// 创建自定义对话框
Dialog<ButtonType> dialog = new Dialog<>();
dialog.setTitle("Custom Dialog");
dialog.setHeaderText("Are you sure?");
dialog.setContentText("Do you want to proceed?");

// 创建关闭按钮
Button closeButton = new Button("Close");
dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL, ButtonType.CLOSE);
dialog.getDialogPane().lookupButton(ButtonType.CLOSE).setVisible(false);

// 设置关闭按钮的事件处理程序
dialog.setOnCloseRequest(event -> {
    event.consume(); // 阻止默认的关闭行为
    // 检查用户选择的选项
    ButtonType result = dialog.getResult();
    if (result == ButtonType.OK) {
        // 用户选择了确定按钮
        // 执行相应的操作
        dialog.close();
    } else if (result == ButtonType.CANCEL) {
        // 用户选择了取消按钮
        // 可以选择不执行任何操作或者执行相应的取消操作
        dialog.close();
    }
});

dialog.showAndWait();

通过以上方法,你可以在用户从JavaFX的对话框中选择一个选项之前防止primaryStage关闭,并根据用户的选择执行相应的操作。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券