如何将单一字体应用于 JavaFX 中的所有文本

How to apply a single font to all text in JavaFX

我正在开发一款软件,它允许您更改它用于显示文本的字体(当我说文本时,我指的是标签、TextArea、按钮等中的文本)。

例如,在我的程序中,我有 6 个标签、4 个按钮和 3 个文本区域以及一个字体对象:

Font myFont = new Font(20);

Label l1 = new Label("text1");
Label l2 = new Label("text2");
Label l3 = new Label("text3");
Label l4 = new Label("text4");
Label l5 = new Label("text5");
Label l6 = new Label("text6");

Button b1 = new Button("button1");
Button b2 = new Button("button2");
Button b3 = new Button("button3");
Button b4 = new Button("button4");

TextArea t1 = new TextArea("text1");
TextArea t2 = new TextArea("text2");
TextArea t3 = new TextArea("text3");

如何将 myFont 应用于这些对象中的每一个,而不必为其中的每一个对象编写 .setFont()?

假设您将所有 LabelsTextFields 添加到 AnchorPane(也适用于其他窗格):

 AnchorPane mainPane = new AnchorPane();
 mainPane.getChildren().addAll(l1, l2, b1, b2, t1,t2);


 // later in your code you can just call `getChildren` Method of the mainPane and loop 
 // over it and set Font with setStyle() like this:
 
 for (int i = 0; i < mainPane.getChildren().size(); i++) {
    mainPane.getChildren().get(i).setStyle("-fx-font-family: YOUR_FONT_NAME; -fx-font-size: 50;");
 }

执行此操作的正确方法是将样式 sheet 应用到您指定 -fx-font 的场景。 参见 https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#typefont

由于 -fx-font 属性被许多 类 继承,您可以通过为根节点指定它来覆盖大部分文本。 https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#introinheritance

我发现在使用 CSS 调整样式时查看内置样式的 CSS 很有帮助: https://github.com/openjdk/jfx/blob/master/modules/javafx.controls/src/main/resources/com/sun/javafx/scene/control/skin/modena/modena.css

https://github.com/openjdk/jfx/blob/master/modules/javafx.controls/src/main/resources/com/sun/javafx/scene/control/skin/caspian/caspian.css

public class Main extends Application {

    public static void main(final String[] args) {
        launch(args);
    }

    @Override
    public void start(final Stage primaryStage) throws Exception {
        String myStyles = """
                         .root {
                           -fx-font: 24 monospace;
                         }
                         """;
        File cssFile = File.createTempFile("demo", "css");
        cssFile.deleteOnExit();
        Files.writeString(cssFile.toPath(), myStyles, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        String cssURL = cssFile.toURI().toString();

        VBox box = new VBox(4,
                new Label("This is a label."),
                new TextField("This is a text field."),
                new Button("This is a button."));
        box.setPadding(new Insets(4));
        Scene scene = new Scene(box);
        scene.getStylesheets().add(cssURL);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}