0

I have a mainController does follow:

@FXML
protected void onPizzaButton(ActionEvent event) throws IOException {
    ...

    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("PiazzaView.fxml"));
    Parent root = (Parent) fxmlLoader.load();

    PizzaController pizzaView = fxmlLoader.getController();
    pizzaView.initialize();
    pizzaView.setMainController(this);
    
    Scene newScene = new Scene(root);
    Stage newStage = new Stage();
    newStage.setScene(newScene);
    newStage.show();
}

And a second controller as follow:

private MainController mainController;

public void setMainController(MainController controller){
    this.mainController = controller;
}

public void initialize(){
    try
    {
        Pizza pizza = mainController.getPizza(); // I keep getting null for 'mainController'
        if (pizza instanceof Deluxe){
            PizzaImage.setImage(new Image("file:Deluxe"));
            pizzaName.setText("Deluxe");
        }
    }
    catch(NullPointerException e)
    {
        System.out.print("NullPointerException Caught");
    }
}

Does anyone have an idea of what's going on? I think I set up my path in two of fxml files correctly, it makes no sense why I don't get anything for my maincontroller setter method.

James_D
  • 201,275
  • 16
  • 291
  • 322
  • 2
    initialize is called by the loader, you should not call it. Initialize is called before you set the main controller, so if initialization depends on the main controller being set, you need to do the initialization work in the method which sets the main controller. For more info see the marked duplicates. – jewelsea Nov 13 '21 at 08:15
  • Does it mean that I have to include my initialize() in my setMainController(MainController controller), or do I directly write the initialize code in the set main method? – DENGHAO SUN Nov 13 '21 at 17:13
  • directly write the initialize code in the set main method – jewelsea Nov 13 '21 at 21:03

0 Answers0