6

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

4

1 回答 1

10

这是设计使然。出于架构原因,css 的覆盖链工作如下:

默认 caspian.css < API 设置 < 用户Scenecss < 用户Parentcss <setStyle()

这是来自css 参考指南的引用:

JavaFX CSS 实现应用以下优先顺序;来自用户代理样式表的样式的优先级低于从代码中设置的值,后者的优先级低于场景或父样式表。内联样式具有最高优先级。来自 Parent 实例的样式表被认为比来自 Scene 样式表的样式更具体。

setStyle()因此,您可以通过使用而不是 API 调用来实现您的目标。尝试运行下一个示例:

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();
}
于 2012-09-08T22:09:42.947 回答