对我得到的 NullPointerException 有点困惑。我正在尝试将 .css 文件添加到我的主类中。这是代码。
//Load FXML file
Parent root = FXMLLoader.load(getClass().getResource("/application/HumansightFirstDraft.fxml"));
// Create scene
Scene scene = new Scene(root, 400, 600);
//Load CSS
scene.getStylesheets().add(getClass().getClassLoader().getResource("/application/application.css").toExternalForm());
// Display application
primaryStage.setScene(scene);
primaryStage.show();`
application.css 和 Main.java 在同一个地方。
这是我的控制台输出。
Jan 10, 2019 8:30:20 AM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 10.0.1 by JavaFX runtime of version 8.0.191
java.lang.NullPointerException
at application.Main.start(Main.java:22)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
这是我的CSS。我只有一个更改,以便更容易测试。
#startSurvey {
-fx-border-radius: 30;
}
这是我在 Eclipse 中看到的目录。
最佳答案
你不需要说 /application/application.css
就这样写application.css
这是因为主类和 css 文件都在同一个父目录中
和所有的fxml文件一样
更新 也有可能是fxml的controller中出现了空指针。
更新 2 感谢
@kleopatra
不要使用 getClass().getClassLoader().getResource()
只需使用 getClass().getResource()
关于java - 将 CSS 添加到 JavaFX 应用程序时出现带有 getResource() 的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54130547/