简体   繁体   中英

How to load css file in JavaFX 2?

Wrote my JavaFX classes in com.xyz.abc package (ex: com.xyz.abc.Sample.java)
and wrote my CSS files in `root/css/styles.css.

How do I load this CSS file into Sample.java ?

在应用开始时将其添加到场景中

scene.getStylesheets().add("path/to/your/stylesheet.css");

See the CSS reference guide for how paths are resolved:

A style sheet URL may be an absolute URL or a relative URL. If a relative URL is given, it is resolved against the base URL of the ClassLoader of the concrete Application class. If, for example, there is a main class com.wicked.cool.ui.Main that extends Application, the relative URL "com/wicked/cool/resources/styles.css" would resolve correctly. The relative URL "../resources/styles.css" would not since the path ".." relative to the root is not a valid path. It is often easier to use the ClassLoader of some class to find the resource. For example, if the "styles.css" file resides in the same package as Main, the following code will give the correct URL: com.wicked.cool.ui.Main.class.getResource("styles.css").toExternalForm()

Note that, beginning with JavaFX 2.1, a URL consisting of only an absolute path (having no scheme or authority) is resolved relative to the base URL of ClassLoader of the class that extends Application. In other words, "/com/wicked/cool/resources/styles.css" is treated as "com/wicked/cool/resources/styles.css". This is consistent with FXML.

So your question isn't quite clear, but if "root" is the classpath of your application, you probably want

scene.getStylesheets().add(getClass().getResource("css/styles.css").toExternalForm());

If "root" is actually a directory in the classpath, then replace "css/styles.css" with "root/css/styles.css".

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