1

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?

2
  • Is there actually an element with class="root"? Commented Nov 10, 2014 at 18:37
  • From documentation - The .root style class is applied to the root node of the Scene instance. Because all nodes in the scene graph are a descendant of the root node, styles in the .root style class can be applied to any node. Commented Nov 10, 2014 at 19:28

1 Answer 1

2

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....

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.