1

I want to create a Programm with FXML. I have multiple FXML-Documents with Controllers for each Documents. But the way I tried to do it does not work beause the Object of the Controller is null.

<HBox fx:id="A" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2"
fx:controller="controllers.AController" alignment="BOTTOM_LEFT">

<Pane fx:id="B" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2"
fx:controller="controllers.BController" HBox.hgrow="ALWAYS" maxWidth="Infinity"/>

2 of them have to know each other.

I imagine it to be like :

FXMLLoader Aloader = new FXMLLoader(getClass().getResource("/views/A.fxml"));
HBox toolbar = ALoader.load();

FXMLLoader Bloader = new FXMLLoader(getClass().getResource("/views/B.fxml"));
HBox toolbar2 = BLoader.load();

Then the AController should recieve the initialized Controller from B.

AContoller ac = Aloader.getController();
BCOntroller bc = Bloader.getController();
ac.setBController(bc);

there is a method in AController that looks like but "getController()" returns a completley new instance of the controller associated with the fxml :

public class AController{
private BContoller bc;

  public void setBController(BController b){
    bc = b;
  }
};
Luxusproblem
  • 1,913
  • 11
  • 23
  • what does this mean Then the AController should recieve the initialized Controller from B. – Rahul Singh Jun 28 '17 at 15:18
  • The code snippet looks like you're creating the loaders in the same scope. But IF this is the case the code snippet would not compile since you're declaring 2 variables with name `toolbar`. Also this should work so the question is: How do you check, if "the Object of the Controller is null"? Also are those 2 fxml files, if this is the case you can separate the code snippets with `` followed by a empty line. – fabian Jun 28 '17 at 15:32
  • Oh sorry I tried to make an easy example and copy pasted some elements of my code and changed them. – Luxusproblem Jun 28 '17 at 15:56
  • 1
    How do you know that the object is null? Typically you will have some initialization logic in your controller inside a method "public void initialize()" which is automatically invoked by the FXMLLoader. However, this is done directly after the fxml file is loaded and before you can get a reference to the controller file out of the FXMLLoader. This means that "initialize" is executed before you can set the other controller. At the time "initialize" is running, the other controller is still null. – Manuel Mauky Jun 28 '17 at 16:04

0 Answers0