Joel
Joel

Reputation: 473

JavaFX and css misunderstanding

In my fxml I have url for css (this fxml created via SceneBuilder)

<AnchorPane>
...
  <stylesheets>
    <URL value="@../styles/test.css" />
  </stylesheets>
</AnchorPane>

and test.css contains

.root{
  ...
}

If I do preview in SceneBuider everything is ok. But in runtime this style doesn't apply. I change definition to

#AnchorPane{
  ... 
}

and this way everynting is ok both in preview and runtime. What's wrong with .root?

Upvotes: 1

Views: 604

Answers (1)

jewelsea
jewelsea

Reputation: 159291

Why it doesn't work

You aren't applying your css to the root node of the scene. You are applying it to the AnchorPane (the <stylesheets> element is a child of the <AnchorPane> element). Therefore if you set a .root css selector for a stylesheet only applied to the AnchorPane, the .root css selector is never going to apply because (as the documentation you quote in your comment states), "the .root style class is applied to the root node of the Scene instance".

Setting a root style class for your pane

You could make it work by setting a .root class on the AnchorPane, for example: <AnchorPane styleClass="root">. Though you may want to use a different style class name (e.g. <AnchorPane styleClass="custom-root"> and leave the .root style class to be reserved for the scene (as overriding .root might have unintended consequences).

Setting a stylesheet for the scene

The other way you could handle it is to not define your css stylesheet in your FXML, but instead to add the css stylesheet to your scene in code using:

scene.getStylesheets().add("/com/example/javafx/app/mystyles.css")

As using .root indicates that you want to change the style for the entire scene, I'd advise using this approach.

If you do so, you can still preview the scene with styles by selecting in SceneBuilder the menu item Preview | Scene Stylesheets | Add a Style Sheet....

Upvotes: 2

Related Questions