Loading css using JavaFX null pointer exception in eclipse


Question

I'm trying to load a CSS file into JavaFX using this line of code and it gives me a null pointer exception:

scene.getStylesheets().add(welcome.class.getResource("background.css").toExternalForm());

My background.css is located in the same folder as the welcome class I have made.

Any idea why I get a null pointer?

Error Log:

Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.access$000(Unknown Source)
    at com.sun.javafx.application.LauncherImpl$1.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NullPointerException
    at welcome.start(welcome.java:164)
    at com.sun.javafx.application.LauncherImpl$5.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$5.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$4$1.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$4$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl$4.run(Unknown Source)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$100(Unknown Source)
    at com.sun.glass.ui.win.WinApplication$3$1.run(Unknown Source)
    ... 1 more
1
3
3/6/2013 1:03:12 AM

Any resource should be on the classpath to be loaded successfully (if it is in the same folder as you welcome class then it is already so). Then you should precede the path to the stylesheet file by '/' symbol, so that it looks like this:

scene.getStylesheets().add(welcome.class.getResource("/background.css").toExternalForm());

Then it will load successfully.

5
5/24/2013 7:44:38 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon