当我尝试从控制器(JavaFX)调用方法时,我得到一个InvocationTargetException,代码如下:
public void start(Stage stage) throws Exception {
URL location = getClass().getResource("startScreen.fxml");
FXMLLoader loader = new FXMLLoader();
loader.setLocation(location);
loader.setBuilderFactory(new JavaFXBuilderFactory());
//Getting hte controller
StartScreenController s = (StartScreenController)loader.getController();
//Where error occurs
s.setParent(this);
Parent root = (Parent) loader.load(location.openStream());
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
当我删除“setParent”行时,它工作正常。
这似乎对其他人有用(就我自己试图解决的问题而言)。
任何帮助将不胜感激,谢谢。
我得到的错误(s.setParent是第38行)
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.javafx.main.Main.launchApp(Main.java:642)
at com.javafx.main.Main.main(Main.java:805)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NullPointerException
at johnsoft.dndcommunication.DndCommunication.start(DndCommunication.java:38)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:206)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
... 1 more
Java Result: 1
答案 0 :(得分:2)
我想,
您正在尝试在加载FXML文件之前访问控制器类。
StartScreenController s = (StartScreenController)loader.getController();
// so StartScreenController s is null here thus NPE
s.setParent(this);
// here loading is happening after getting the controller class, which is wrong.
// Get the controller after loading is completed.
Parent root = (Parent) loader.load(location.openStream());