简体   繁体   中英

How do I dynamically add and remove css for the whole JavaFX application?

I'm using JDK8 build 87 and would like to dynamically add and remove css stylesheets such that they can be used by my whole JavaFX application.

At the moment I'm setting the default styleSheet using this command:

Application.setUserAgentStylesheet(Application.STYLESHEET_MODENA);

and then when I want to add an additional css style sheet I do this:

com.sun.javafx.css.StyleManager.getInstance.addUserAgentStylesheet(styleSheet);

This works but I have two problems. Firstly, it is using a private API and secondly there doesn't seem to be a way to remove it once I have finished with it (I'm using OSGI so it is common for modules to come and go).

There was talk about moving StyleManager to public API at the start of 2012 but I'm not sure anything has happened about that.

Does anyone know of a public method to add styleSheets such that they apply to the whole JavaFX application? Also how would one remove them?

(I don't have the privileges to create the new javafx-8 tag)

According to Global Stylesheet for your GUI application :

// load default global stylesheet
Application.setUserAgentStylesheet(null);
// add custom global stylesheet
StyleManager.getInstance().addUserAgentStylesheet(AQUA_CSS_NAME);

However as Boomah points out, StyleManager.getInstance().addUserAgentStylesheet is not part of the JavaFX API, so this method is really not recommended that it be used directly from user code. Additionally, it only works for adding a global stylesheet and not for removing a such a stylesheet once the stylesheet has been added.


The more adventurous could create a patch to add Boomah's suggested feature by modifying the StyleManager code to support removal of global stylesheets and modifying Application class source code to provide a public API for the new feature which makes use of the updated StyleManager , then submit the patch to openjfx-dev for inclusion in the JavaFX platform.


In the meantime you can manually set your user stylesheet on each of your application's scenes - kind of pain, but there you are . . .

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