In JavaFX, there are many ways to skin a application, I’ll take a look at three methods of dynamically loading a css file into your JavaFX application.
There are a many advantages to placing your style rules inside of a CSS file; It keeps your style rules in one central location, allows the application’s logic and design to be seperated from each other, as well as allowing for the look of the application to be changed on the fly without needing to recompile the jar each time. You can of course set the style of an individual Node using Node.setStyle(), but as we’ve found in our combined Swing and JavaFX Viewer, this can start to get out of hand and at some point you need to reign it in.
The example application I’m using can be found on my Github.
1. From Compiled Jar
This stylesheet is the one included in the compiled jar for this project. The code to load it is as follows:
String css = DynamicCSS.class.getResource("/jarcss.css").toExternalForm(); scene.getStylesheets().clear(); scene.getStylesheets().add(css);
The last two lines are fairly straightforward: Remove all current stylesheets in use and use our one. The first line gets the absolute path on disk to the file inside of the jar file with a string representation with a form similar to “jar:path/to/application.jar!/stylesheet.css” which tells the application that the file is located inside of a compiled java application.
2. From File
You can also load a stylesheet for your application from your file system. This can be done by changing:
File f = new File("filecss.css"); scene.getStylesheets().clear(); scene.getStylesheets().add("file:///" + f.getAbsolutePath().replace("\\", "/"));
There are two things to be aware of when loading from disk; First of all, JavaFX uses URLs to resolve the file location, so the prefix “file:///” is needed when loading from disk. Secondly, you can’t mix and match your slashes, so backslashes have to be converted to forward slashes.
3. From the Web
As we can add CSS via URLs, we can also load in CSS files from the internet. To do this, we simply provide the location of the file:
There are multiple ways of setting a personalised style in JavaFX using CSS. There are no wrong answers to which one you want to use, but ultimately it comes down to where you want control to lie. If you want control over the style then options 1 and 3 would be the best depending on the context – Option 1 if you want the CSS to be updated with every build or 3 if you want the CSS to be consistent across all versions. If you want the user to have more control over the CSS, then option 2 is the best solution.
This post is part of our “Java Articles Index“ series. In these articles, we aim to explore the world of Java and Javafx. Have a look through!
Can we help you to solve any of these problems?
IDRsolutions has been helping companies to solve these problems since 1999.
|Convert PDF to HTML5 or SVG||Convert PDF forms to HTML5|
|Java SDK for Image files||Java SDK for PDF files|