How to create a JavaFX alert with the "Don't ask again" checkbox?

I would like to use the standard JavaFX class Alertfor the confirmation dialog, which includes the "Don't ask again" checkbox. Is this possible, or do I need to create a custom one Dialogfrom scratch?

I tried to use the method DialogPane.setExpandableContent(), but this is not exactly what I want - it adds a Hide / Show button on the button bar and a checkbox will appear in the main part of the dialog box, while I want to check to see it appear on the button bar.

+4
source share
1 answer

, , . DialogPane.createDetailsButton(), node, "/". , Alert, , Alert. DialogPane, , , . factory 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;
}

factory, 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

+5

All Articles