有没有办法在警报按钮上设置字体?

Is there a way to set the font on an Alert button?

我正在寻找一种方法来为 AlertType = WARNING 的 javafx.scene.control.Alert“确定”按钮设置特定字体。有谁知道这是否可行,如果可行,如何实现?

感谢任何建议。

正如 Slaw 在他的评论中所写,有一个 lookupButton method 可用:

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).

因此您可以像这样简单地使用它来设置新字体:

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

或者你可以这样做:

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

编辑(在评论区回答一个问题):

如果你想使用专用的 css 文件,你可以这样做:

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;
}

如果你不仅想要按钮的样式,你可以看看这个