JavaFX: unable to set font size programmatically after font is set using CSS

I saved the default font type and size for my application in a CSS file that I use with the code:

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

However, I also added a function that, if the user provides their own preferences, should override the default settings (specified above) and use the font size provided by the user:

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

In this case, calling label.setFont() does not set the new size specified by the user. When I comment on CSS source code, later work.

Any workaround?

Note: cross reference to JavaFX forum

+5
source share
1 answer

This is by design. For architectural reasons, the CSS override chain works as follows:

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

Here is a quote from the CSS reference :

The JavaFX CSS implementation applies the following priority order; A style from a user agent stylesheet has a lower priority than a value set from code that has a lower priority than a Scene or Parent stylesheet. Inline styles have the highest priority. Style sheets from the parent instance are considered more specific than styles from Scene style sheets.

That way you can achieve your goal using setStyle() instead of calling the API. Try running the following 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 (does not 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(); } 
+10
source

Source: https://habr.com/ru/post/1433163/


All Articles