Steve Wolf
Steve Wolf

Reputation: 123

JavaFX - Set default CSS stylesheet for the whole Application

I'm pretty new to JavaFX, I'm trying to change my application aspect via CSS. First time it works fine, when I switch to another scene CSS' classes are not applied. Because my project has 10 scenes, I prefer to use a single CSS file to apply my style to all scenes by using this statement: StyleManager.getInstance().addUserAgentStylesheet(this.getClass().getResource("/style.css").toExternalForm()); into start() method. How can I apply to all scenes my CSS file globally?

Upvotes: 2

Views: 3960

Answers (1)

DVarga
DVarga

Reputation: 21799

You can do it with the following two lines:

Application.setUserAgentStylesheet(Application.STYLESHEET_MODENA);
StyleManager.getInstance().addUserAgentStylesheet(getClass().getResource("/style.css").toString());

The first line will set the default stylesheet to modena (here you could even choose to set JavaFX2 caspian as default stylesheet) using Application#setUserAgentStylesheet, while the second line will add your stylesheet to the user agent stylesheet list.

It's not the nicest solution as StlyeManager is a private API (and will remain in JDK9 as it is now).


Other solution would be to subclass Scene, in which subclass you can add your stylesheet by default, then rather than instantiating Scene, you could create instances of your subclass.

Upvotes: 4

Related Questions