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">
...
It's possible to use the same controller class for multiple FXML files, but your code will be really hard to follow, and it's a very bad idea. (Also note that using the fx:controller attribute, you will have a different controller instance each time you call FXMLLoader.
JavaFX controller works based on MVC(Model-View-Controller) JavaFX MVC can be achieved by FXML (EFF-ects eXtended Markup Language). FXML is an XML based language used to develop the graphical user interfaces for JavaFX applications as in the HTML.
FXML is an XML-based language that provides the structure for building a user interface separate from the application logic of your code.
The @FXML annotation is required for the controller class's private member fields; otherwise, field injection would fail.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With