gpt4 book ai didi

java - 调用 Controller 方法时出现 InspirationTargetException - JavaFX

转载 作者:行者123 更新时间:2023-11-30 04:30:21 25 4
gpt4 key购买 nike

当我尝试从 Controller (JavaFX)调用方法时,我收到一个 InvocableTargetException 异常,代码如下:

    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

最佳答案

我猜,
您正尝试在加载 FXML 文件之前访问 Controller 类。

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());

关于java - 调用 Controller 方法时出现 InspirationTargetException - JavaFX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14791961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com