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
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.
Did you initialize the Scene object yet?
//Create a scene object. Pass in the layout and set with and height
this.scene = new Scene(layout, 600, 400);
//Add CSS Style Sheet (located in same package as this class).
String css = this.getClass().getResource("background.css").toExternalForm();
scene.getStylesheets().add(css);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With