JavaFX - How to get FXML Controller?


Question

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">
    ...
1
9
9/13/2014 11:09:19 PM

Accepted Answer

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:

29
5/23/2017 12:02:31 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon