简体   繁体   English

JavaFX-为整个应用程序设置默认的CSS样式表

[英]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. 我对JavaFX非常陌生,我正尝试通过CSS更改应用程序方面。 First time it works fine, when I switch to another scene CSS' classes are not applied. 第一次工作正常,当我切换到另一个场景时,CSS的类未应用。 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()); 因为我的项目有10个场景,所以我更喜欢使用一个CSS文件通过以下语句将样式应用于所有场景: StyleManager.getInstance().addUserAgentStylesheet(this.getClass().getResource("/style.css").toExternalForm()); into start() method. 进入start()方法。 How can I apply to all scenes my CSS file globally? 如何在全局范围内将CSS文件应用于所有场景?

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. 第一行使用Application#setUserAgentStylesheet将默认样式表设置为Modena(在这里您甚至可以选择将JavaFX2里海设置为默认样式表),而第二行将样式表添加到用户代理样式表列表中。

It's not the nicest solution as StlyeManager is a private API (and will remain in JDK9 as it is now). 这不是最好的解决方案,因为StlyeManager是私有API(并且现在将保留在JDK9中)。


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. 其他解决方案是子类Scene ,默认情况下,您可以在该子类中添加样式表,然后可以实例化子类的实例,而不是实例化Scene

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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