M Lev M Lev - 5 months ago 38
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);
primaryStage.setScene(scene);
scene.getStylesheets().add(Login.class.getResource("Login.css").toExternalForm());
primaryStage.show();


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:

C:\Users\XXXXXXXX\IdeaProjects\Login\src


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
C:\Users\XXXXXXXX\IdeaProjects\Login\src\sample\Main.java
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

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):

scene.getStylesheets().add(sample.Main.class.getResource("/Login.css").toExtern‌​alForm());
Comments