1

I am looking for a way to set a specific font for the javafx.scene.control.Alert "OK" button for AlertType = WARNING. Does anyone know whether this is possible and, if so, how this is done?

Thanks for any advice.

BZKN
  • 1,499
  • 2
  • 10
  • 25
Bob
  • 83
  • 6
  • 2
    You can get access to the button via `DialogPane#lookupButton(ButtonType)` to set the font programmatically. Or you could use CSS. – Slaw Apr 17 '21 at 23:08

1 Answers1

2

As Slaw wrote in his comment there is a lookupButton method available:

This method provides a way in which developers may retrieve the actual Node for a given ButtonType (assuming it is part of the button types list).

So you can simply use it like this to set a new font:

alert.getDialogPane().lookupButton(ButtonType.OK).setStyle("-fx-font-family: Vijaya;");

or you can do:

((Button) alert.getDialogPane().lookupButton(ButtonType.OK))
                    .setFont(new Font("Vijaya", 12));

Edit (answer to a question in the comment section):

If you want to use a dedicated css file, you can do it like this:

Alert alert = new Alert(Alert.AlertType.WARNING);
DialogPane dialogPane = alert.getDialogPane();

// because the alert is a new stage, you have to reference the style sheet you want to use:
dialogPane.getStylesheets().add(App.class.getResource("alerts.css").toExternalForm());

// find the button and give it an id:
Button okBtn = (Button) dialogPane.lookupButton(ButtonType.OK);
okBtn.setId("ok-btn");

alerts.css:

#ok-btn {
    -fx-font-family: Vijaya;
}

If you want to style not only the button, you can have a look at this answer.

anko
  • 1,628
  • 1
  • 6
  • 14
  • Again, excellent! Works perfect. I didn't know that about the Alert being in a new stage. Interesting. Anko, Slaw, thank you so much! I've learned a lot. :-) – Bob Apr 18 '21 at 19:07
  • Thank for response :) What about the ContentText and the HeaderText ? is it possible to change the default Font ? – Aguid Oct 10 '22 at 09:26