M Lev M Lev - 2 years ago 177
Java Question

JavaFX 8: Adding a Custom CSS File Via class.getResource() Error

I am working through the official JavaFX tutorial. I am trying to add the code from Example 5-1 as follows to my scene, which is part of the "Main" class as per the instructions:

Scene scene = new Scene(grid, 300, 275);

I'm using JavaFX runtime version 8.0.72-b15 and IntelliJ IDEA 15.0.5. I have stored my "Login.css" file in the folder:


and my project files are structured as follows:

  • Login

    • .idea

    • out

    • src

      • sample

        • Controller.java

        • Main.java

        • sample.fxml

      • background.jpg

      • Login.css

When I run "Main" I get the following error message:

Information:Using javac 1.8.0_77 to compile java sources
Information:java: Errors occurred while compiling module 'Login'
Information:6/9/2016 2:04 PM - Compilation completed with 1 error and 0 warnings in 571ms
Error:(69, 36) java: cannot find symbol
symbol: class Login
location: class sample.Main

This answer seems to imply that the custom CSS file should be under the "src" folder, but it doesn't appear to be working for me. How can I get my JavaFX project to import this custom CSS file?

Answer Source

You don't have a Login class... you only have a sample.Main class, so the Login.class reference in your code won't resolve (that error is unrelated to CSS).

Once you fix the class reference error, you also need to fix the reference to the css file location (as your Login.css file is not in the sample package, but is instead in the source root, so it will eventually be copied to the root of your classpath). To reference a resource in the root of the classpath, prepend / to the resource name, i.e. /Login.css.

So, after these changes, you have, the following code (which you verified works in previous comments):

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download