Search code examples
javacontrollerjavafx-2invocationtargetexception

InvocationTargetException when calling a controllers method - JavaFX


I get an InvocationTargetException when I try to call a method from the controller (JavaFX), the code goes as follow:

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

It works fine when I remove the "setParent" line.

This seem to have worked for others (as far as from what I have seen when trying to solve this myself).

Any help would be appreciated, thanks.

The error I get (s.setParent is line 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

Solution

  • I guess,
    you are trying to access to the controller class before loading the FXML file.

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