JavaFX - How to get FXML Controller?

ceklock picture ceklock · Sep 14, 2014 · Viewed 33.1k times · Source

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">
    ...

Answer

jewelsea picture jewelsea · Sep 14, 2014

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: