Mehdi LAMRANI
Mehdi LAMRANI

Reputation: 11597

JavaFX : When/Where are elements/controls instantiated?

All right, I have my first JFX App Up & Running.

Now, I am asking myself how everything is nicely wrapped-up behind the scene. How is all this bunch of FXML transformed into java code with proper instantiation and all ? How does it work ?

I'd Google that if I knew what to write but so far I find a lot about how to use it but not much about how it is made.

Upvotes: 1

Views: 122

Answers (1)

DVarga
DVarga

Reputation: 21799

The magic happens inside the FXMLLoader.

It receives an FXML file, and parses it with an XML parser. You are forced to use a well-defined set of XML nodes, and the loader knows how to "transform" every type of these XML nodes to the corresponding java object (to a JavaFX Node) at runtime. If the format of the XML file is not correct (does not fit the defined structure) you will get an exception. This way your nodes are created, one thing left: populate the controller.

To populate the controller, it will use reflection to create an instance of the specified controller class and to set its data members. It iterates through the @FXML annoted fields inside and then set each of them to one of the created objects with the matching fx:id attribute.

In the end by default the public initialize method is called on the controller instance.

Upvotes: 2

Related Questions