How to change the text of yes/no buttons in JavaFX 8 Alert dialogs

27,189

Solution 1

You can define your own button types. In this example the buttons' text is foo and bar:

ButtonType foo = new ButtonType("foo", ButtonBar.ButtonData.OK_DONE);
ButtonType bar = new ButtonType("bar", ButtonBar.ButtonData.CANCEL_CLOSE);
Alert alert = new Alert(AlertType.WARNING,
        "The format for dates is year.month.day. "
        + "For example, today is " + todayToString() + ".",
        foo,
        bar);

alert.setTitle("Date format warning");
Optional<ButtonType> result = alert.showAndWait();

if (result.orElse(bar) == foo) {
    formatGotIt = true;
}

Solution 2

((Button) dialog.getDialogPane().lookupButton(ButtonType.OK)).setText("Not OK Anymore");
((Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL)).setText("Not Cancel Anymore");
Share:
27,189

Related videos on Youtube

coderodde
Author by

coderodde

You know me.

Updated on February 26, 2020

Comments

  • coderodde
    coderodde about 4 years

    I have this code snippet:

    Alert alert = 
            new Alert(AlertType.WARNING, 
                "The format for dates is year.month.day. " +
                "For example, today is " + todayToString() + ".",
                 ButtonType.OK, 
                 ButtonType.CANCEL);
    alert.setTitle("Date format warning");
    Optional<ButtonType> result = alert.showAndWait();
    
    if (result.get() == ButtonType.OK) {
        formatGotIt = true;
    }
    

    Above, I request two buttons titled "Yes" and "No." However, I wish to change them both.

  • Miss Chanandler Bong
    Miss Chanandler Bong about 6 years
    Actually, I find this might be useful to someone. Especially in case of JavaFx dialog like Alert. Example: Alert errorAlert = new Alert(Alert.AlertType.ERROR);
  • KenobiBastila
    KenobiBastila over 3 years
    its Very Relevant, solved my issue. Just remember that 'dialog' might also be a "Alert" object.