JavaFX CSS root property reference not resolved


Question

JavaFX documentation seems to imply that if a property is defined in the CSS root class it can be referred to by any object in the scene:

The .root style class includes properties that can be used by other styles to provide consistency in a UI. For example, the property -fx-focused-base is defined in the .root style. This property is used by styles for other UI controls as the color for the control when it has focus.

For example, in the following simple application:

public class Main extends Application {

@Override
public void start(Stage stage) throws Exception {
    AnchorPane pane = new AnchorPane();
    Scene s = new Scene(pane, 800, 600);

    pane.getStylesheets().add("test.css");
    pane.getStyleClass().add("test");

    System.out.println("Root pane style classes:");
    for (String clazz : pane.getStyleClass())
        System.out.println(clazz);

    stage.setScene(s);
    stage.show();
}

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

With the following stylesheet test.css:

.test {
-fx-background-color: -fx-base;
}

Results in the following output:

Root pane style classes:
root
test
WARNING: com.sun.javafx.css.StyleHelper calculateValue Could not resolve '-fx-base' while resolving lookups for '-fx-background-color' from rule '*.test' in stylesheet test.css

(I removed the file path from the warning)

Why isnt it able to resolve -fx-base? It is clearly included in caspian.css...

1
3
11/16/2012 11:05:22 PM

Accepted Answer

It appears the issue here is that the stylesheet (caspian.css) is lazily loaded. Therefore, unless a component is constructed (not even necessarily added) the stylesheet is not resolved. Layout containers (like AnchorPane) do not trigger loading of the stylesheet. On the other hand, Controls (like Button/CheckBox/Label etc.) will trigger the stylesheet to be loaded.

Here is an updated version of the test case above to illustrate this behavior:

public class Main extends Application {

@Override
public void start(Stage stage) throws Exception {
    AnchorPane pane = new AnchorPane();

    new Button(); // Trigger loading of default stylesheet

    Scene s = new Scene(pane, 800, 600);
    pane.getStylesheets().add("test.css");
    pane.getStyleClass().add("test");

    System.out.println("Root pane style classes:");
    for (String clazz : pane.getStyleClass())
        System.out.println(clazz);

    stage.setScene(s);
    stage.show();
}

public static void main(String[] args) {
    Application.launch();
}
}
5
3/10/2016 4:42:06 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon