JavaFX: Cannot set font size programmatically after font being set by CSS

坚强是说给别人听的谎言 提交于 2019-12-18 06:54:38

问题


I have stored the default font type and size of my application in a CSS file which I apply using the code:

label.getStyleClass().add("labelStyleClass");

However I also added the feature that if the user provides its own preference, it should override the default settings (set above) and use the user provided font size:

double userSize = readFromFile;
label.setFont(new Font(userSize));

In this case the label.setFont() call does not set the new size given by user. When I comment out the initial CSS code, the later works.

Any workaround?

Note: cross-posted at JavaFX forum


回答1:


It's by design. For architectural reasons chain of overrides for css works as follows:

default caspian.css < API settings < user's Scene css < user's Parent css < setStyle()

Here is the quote from css reference guide:

The JavaFX CSS implementation applies the following order of precedence; a style from a user agent style sheet has lower priority than a value set from code, which has lower priority than a Scene or Parent style sheet. Inline styles have highest precedence. Style sheets from a Parent instance are considered to be more specific than those styles from Scene style sheets.

Thus, you can achieve your goal by using setStyle() instead of an API call. Try to run the next example:

public void start(Stage stage) {
    VBox root = new VBox(10);

    Scene scene = new Scene(root, 300, 250);
    // font.css: .labelStyleClass { -fx-font-size: 20 }
    scene.getStylesheets().add(getClass().getResource("font.css").toExternalForm());

    root.getChildren().add(LabelBuilder.create().text("default").build());
    root.getChildren().add(LabelBuilder.create().text("font-css").styleClass("labelStyleClass").build());

    Label lblApi = LabelBuilder.create().text("font-css-api (doesn't work)").styleClass("labelStyleClass").build();
    lblApi.setFont(Font.font(lblApi.getFont().getFamily(), 40));
    root.getChildren().add(lblApi);

    Label lblStyle = LabelBuilder.create().text("font-css-setstyle (work)").styleClass("labelStyleClass").build();
    lblStyle.setStyle("-fx-font-size:40;");
    root.getChildren().add(lblStyle);

    stage.setTitle("Hello World!");
    stage.setScene(scene);
    stage.show();
}


来源:https://stackoverflow.com/questions/12333985/javafx-cannot-set-font-size-programmatically-after-font-being-set-by-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!