javafx - 如何创建带有 "Do not ask again"复选框的 JavaFX 警报?

标签 javafx

我想使用标准的 JavaFX Alert包含“不再询问”复选框的确认对话框类。这可能吗,还是我必须创建一个自定义 Dialog从头开始?

我尝试使用 DialogPane.setExpandableContent()方法,但这并不是我真正想要的 - 这会在按钮栏中添加一个隐藏/显示按钮,并且复选框出现在对话框的主体中,而我希望复选框出现在按钮栏中。

最佳答案

是的,这是可能的,只需做一点工作。您可以覆盖 DialogPane.createDetailsButton()返回您想要的任何节点来代替隐藏/显示按钮。诀窍是您需要重建Alert之后,因为您将摆脱Alert 创建的标准内容。 .你还需要愚弄DialogPane考虑有扩展的内容,以便它显示您的复选框。这是创建 Alert 的工厂方法示例带有选择退出复选框。复选框的文本和操作是可定制的。

public static Alert createAlertWithOptOut(AlertType type, String title, String headerText, 
               String message, String optOutMessage, Consumer<Boolean> optOutAction, 
               ButtonType... buttonTypes) {
   Alert alert = new Alert(type);
   // Need to force the alert to layout in order to grab the graphic,
    // as we are replacing the dialog pane with a custom pane
    alert.getDialogPane().applyCss();
    Node graphic = alert.getDialogPane().getGraphic();
    // Create a new dialog pane that has a checkbox instead of the hide/show details button
    // Use the supplied callback for the action of the checkbox
    alert.setDialogPane(new DialogPane() {
      @Override
      protected Node createDetailsButton() {
        CheckBox optOut = new CheckBox();
        optOut.setText(optOutMessage);
        optOut.setOnAction(e -> optOutAction.accept(optOut.isSelected()));
        return optOut;
      }
    });
    alert.getDialogPane().getButtonTypes().addAll(buttonTypes);
    alert.getDialogPane().setContentText(message);
    // Fool the dialog into thinking there is some expandable content
    // a Group won't take up any space if it has no children
    alert.getDialogPane().setExpandableContent(new Group());
    alert.getDialogPane().setExpanded(true);
    // Reset the dialog graphic using the default style
    alert.getDialogPane().setGraphic(graphic);
    alert.setTitle(title);
    alert.setHeaderText(headerText);
    return alert;
}

这是正在使用的工厂方法的示例,其中 prefs是一些保存用户选择的偏好商店
    Alert alert = createAlertWithOptOut(AlertType.CONFIRMATION, "Exit", null, 
                  "Are you sure you wish to exit?", "Do not ask again", 
                  param -> prefs.put(KEY_AUTO_EXIT, param ? "Always" : "Never"), ButtonType.YES, ButtonType.NO);
    if (alert.showAndWait().filter(t -> t == ButtonType.YES).isPresent()) {
       System.exit();
    }

这是对话框的样子:

enter image description here

关于javafx - 如何创建带有 "Do not ask again"复选框的 JavaFX 警报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36949595/

相关文章:

java - 如何将值传递给在方法的 Controller 类中调用新页面的方法?

JavaFX 启动内部应用程序类

java - 如何关闭 Java 中 TextArea 中闪烁的光标?

gradle - 如何将 --add-exports 添加到 gradle 应用程序?

java - 控件的首选大小是多少?

java - javafx 中的按钮

java - 在 JavaFX 中使用 vert.x http 服务器

javafx - 使用 slider 更改文本颜色

java - 明确新线程启动和停止的时间和地点

javafx-2 - 我们可以在 JAVAFX 中使用创建和使用自定义 EventHandler 类吗?