我正在尝试使用这行代码将 CSS 文件加载到 JavaFX 中,它给了我一个空指针异常:
scene.getStylesheets().add(welcome.class.getResource("background.css").toExternalForm());
我的 background.css
与我创建的欢迎类位于同一文件夹中。
知道为什么我得到一个空指针吗?
错误日志:
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
请您参考如下方法:
任何资源都应该在类路径上才能成功加载(如果它与您的欢迎类位于同一文件夹中,那么它已经如此)。然后你应该在样式表文件的路径前加上“/”符号,这样它看起来像这样:
scene.getStylesheets().add(welcome.class.getResource("/background.css").toExternalForm());
然后会加载成功。