简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM