The fx:id attribute
Most nodes can have an "fx:id". This attribute names a Java variable of the same type of the
node. When the FXML is parsed, the variable will be updated to contain the reference to the node.
For example, if we define a label in FXML as:
<Label fx:id="myLabel" text="HelloWorld" />
then in the corresponding Java controller class:
@FXML
private Label myLabel;
The variable with the same name as the "fx:id" will be bound to that instance of the node.
When an fx:id attribute is found, we can think of this as creating an FXML named variable with
the value of the fx:id referencing the element to which it is attached. In other elements we can
refer to the element with the fx:id using the "$<name>" syntax.
We can also use an additional syntax that looks like "${<name>.<property>}" to dynamically
have an element's property bound to another elements property.
The fx:root element
The fx:root element is used to declare that the root element will NOT be created but rather will
be set by a call to to setRoot() prior to the load() method being called.
A Controller class
A controller class fulfills the controller part of the Model-View-Controller contract. An FXML
described application can name a controller class using the fx:controller attribute.
A method called "initialize()" can/should be implemented in the controller and will be called
to initialize an variables or data.
For example:
@FXML
private void initialize() {
// Do some initialization ...
}
The controller class can include variables that are injected/mapped to the fx:id references for
FXML elements. For example, if we define:
<TextField fx:id="myText"/>
then in the controller class, we can specify:
@FXML
private TextField myText;
and when the Controller is instantiated, the "myText" variable will be automatically set to be a
referenced to the corresponding JavaFX TextField object.
For JavaFX widgets that can emit events, we can define functions within the controller class that
can be invoked to process such events.
For example:
@FXML
private void myHandler(ActionEvent event) {
// do something
}
And in the FXML, we can map the widget to this function using:
Page 258
Kommentare zu diesen Handbüchern