Nielsou Akbrg Nielsou Akbrg - 4 months ago 17
Java Question

Not possible to point to the adress of the JavaFX-controller of a newly loaded FXML

I'm loading several FXML-files and try to set members in their respective controllers. However in some mysterious cases, I am not able to point to the controller of the loaded FXML At first I thought it was only the controllers implementing 'Initialize' but after some tests, it's not the case.

Here is some codes and the core stack :

public void showLoginScreen() {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/Login.fxml"));
mMainScene.setRoot((Parent) loader.load());
LoginController controller = loader.<LoginController>getController();
//I am able to reach the controller from here
controller.initManager(this);
} catch (IOException ex) {
Logger.getLogger(ControllerManager.class.getName()).log(Level.SEVERE, null, ex);
}
}

public void showMainView(String sessionID) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/Main.fxml"));
mMainController = loader.<MainController>getController();
mMainScene.setRoot((Parent) loader.load());
//TODO : I am not able to reach the controller from here
System.out.println("pointer adress = " + mMainController);
mMainController.initManager(this);
} catch (IOException ex) {
Logger.getLogger(ControllerManager.class.getName()).log(Level.SEVERE, null, ex);
}
}


CORE STACK :

pointer adress = null

Caused by: java.lang.NullPointerException
at controller.ControllerManager.showMainView(ControllerManager.java:40)
at view.LoginController.handle(LoginController.java:49)
... 58 more

Answer

In the second case, you are trying to retrieve the controller before you load the FXML. Since the controller class is defined in the FXML file, the loader can't instantiate it until the FXML is loaded.

Just change the order of the method calls:

public void showMainView(String sessionID) {
    try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/Main.fxml"));
        // mMainController = loader.<MainController>getController();
        mMainScene.setRoot((Parent) loader.load());

        mMainController = loader.<MainController>getController();

        System.out.println("pointer adress = " + mMainController);
        mMainController.initManager(this);
    } catch (IOException ex) {
        Logger.getLogger(ControllerManager.class.getName()).log(Level.SEVERE, null, ex);
    }
}