Search code examples
javafxcontrollernestedfxmlsubcontroller

Subcontroller loses passed data from MainController


I have searched this problem for days now and can't find a solution. I have a MainController which is supposed to hold an ArrayList. When I start the Application the SubController is supposed to be initialised in the initialize() method of the MainController. It does work, but if i try to refer on the ArrayList from the MainController from another method in the SubController I always get a NullPointerExeption and I have no idea why. Here is my Code.

Controller.java:

public class Controller {

    public ArrayList<Film> filme = new ArrayList<Film>();

    @FXML Controller1 controller1 = new Controller1();

    ...

    @FXML
    public void initialize() {
        ...
        controller1.init(this);
        ...
    }

    ...
}

Rahmen.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>


<AnchorPane xmlns:fx="http://javafx.com/fxml/1" 
xmlns="http://javafx.com/javafx/8" fx:controller="GUI.Controller" 
fx:id="test">
    <!-- TODO Add Nodes -->
    <fx:include fx:id="tab1" source="StartBildschirm.fxml" />
</AnchorPane>

Controller1.java:

public class Controller1 {

    private Controller main;

    @FXML private Pane film1;

    public void init(Controller controller) {
        main = controller;
        System.out.println(main.filme.get(0).getTitel());
    }

    @FXML
    public void test(MouseEvent e) {

        System.out.println(main.filme.get(0).getTitel());
    }

    ...
}

StartBildschirm.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefWidth="1040.0" xmlns="http://javafx.com/javafx/8" 
xmlns:fx="http://javafx.com/fxml/1" fx:controller="GUI.Controller1">

...

</AnchorPane>

The first Syso works just fine and gives me the correct value, but as I said, the second one always has a NullPointerExeption. Does anyone has an idea on how to getting it fixed?


Solution

  • You're creating a new instance of the Controller1 class that is not used with any fxml instead of using the instance used with the included fxml. To inject the controller of a included fxml to a field of the controller for the fxml containing the <fx:include> the name of the field needs to be the fx:id of the <fx:include> element concatenated with "Controller" i.e. in your case

    @FXML
    private Controller1 tab1Controller;