15

I have the following code:

Parent parent = FXMLLoader.load(Main.class.getResource("JanelaPrincipal.fxml"));

in the fxml file there is a reference to the controller class. How can I get the controller object?


fxml:

<AnchorPane id="AnchorPane" fx:id="root" 
    prefHeight="768.0" prefWidth="1024.0" xmlns:fx="http://javafx.com/fxml/1" 
    xmlns="http://javafx.com/javafx/2.2" 
    fx:controller="br.meuspila.javafx.JanelaPrincipalController">
    ...
ceklock
  • 6,143
  • 10
  • 56
  • 78

1 Answers1

35

Instantiate an FXMLLoader and use an instance load method rather than a class static load method. You can then retrieve the controller instance from the loader instance.

FXMLLoader loader = new FXMLLoader(
  getClass().getResource(
    "customerDialog.fxml"
  )
);

Pane pane = (Pane) loader.load();

CustomerDialogController controller = 
    loader.<CustomerDialogController>getController();
controller.initData(customer);

For more info see:

Community
  • 1
  • 1
jewelsea
  • 150,031
  • 14
  • 366
  • 406
  • 1
    That is really helpful . Thanks – Madushan Perera Mar 19 '17 at 08:22
  • 2
    yup, this was a very helpful answer! Also make sure that when you are making an instance of the FXMLLoader class, that you do it as shown in this answer (by also specifying the .fxml file). I was doing it as just new FXMLLoader(); and that was giving a me a Null pointer exception later when I tried to access the controller for the fxml template file. – user2407334 Jul 16 '17 at 16:08