Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading css using JavaFX null pointer exception in eclipse

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
like image 956
Kimmy Avatar asked Jun 04 '26 11:06

Kimmy


2 Answers

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.

like image 160
akhilless Avatar answered Jun 06 '26 23:06

akhilless


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);
like image 38
medokr Avatar answered Jun 07 '26 00:06

medokr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!