Loading CSS files from the JavaFX code
Let's look more thoroughly at the options we have to select a CSS file to load.
The first way is to use the full folder path to the file:
scene.getStylesheets().add("/chapter6/basics/style.css");
This approach works reliably only if you store your CSS files in a separate resource folder. If your CSS lies along the Java code, any refactoring of the packages may miss this String
constant. In this case, the better option will be to use a relative path:
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
By this call, we tell JavaFX to look for style.css
in the same folder as a current class file.
And the last option is to not store CSS within your project at all but load it from the web:
scene.getStylesheets().add("https://raw.githubusercontent.com/sgrinev/mastering-javafx-9-10-book/master/Chapter6/src/chapter6/basics/style.css");
Although keep in mind that loading CSS happens on the UI thread and the web option in the event of a...