JavaFX - Set default CSS stylesheet for the whole Application

筅森魡賤 提交于 2020-02-05 07:40:12

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/46559981/javafx-set-default-css-stylesheet-for-the-whole-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!