Java Reference
In-Depth Information
Understanding the @FXML Annotation
We have seen two uses of the @FXML annotation. It can be applied to fields in the controller of an FXML file whose
name and type match the fx:id attribute and element name of an FXML element to be injected with the node. It
can be applied to void methods that take either no parameter or one parameter of type javafx.event.Event or its
subtype, making them eligible for use as event handlers for elements in FXML files.
The FXMLLoader will inject its location and resources into the controller if it has the fields to receive them:
@FXML
private URL location;
@FXML
private ResourceBundle resources;
The FXMLLoader will also invoke an @FXML annotated initialization method with the following signature:
@FXML
public void initialize() {
// ...
}
The FXMLInjectionExample in Listings 3-7, 3-8, and 3-9 illustrates how these features work. In this example, we
put four Label s in a VBox in the FXML file. We inject two of the Label s into the controller. We also specify the location
and resources injection fields in the controller class. Finally, in the initialize() method, we set the text of the two
injected Label s to the string representations of location and resource .
Listing 3-7. FXMLInjectionExample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<VBox alignment="CENTER_LEFT"
maxHeight="-Infinity"
maxWidth="-Infinity"
minHeight="-Infinity"
minWidth="-Infinity"
prefHeight="150.0"
prefWidth="700.0"
spacing="10.0"
xmlns=" http://javafx.com/javafx/8 "
xmlns:fx=" http://javafx.com/fxml/1 "
fx:controller="FXMLInjectionExampleController">
<children>
<Label text="Location:">
<font>
<Font name="System Bold" size="14.0"/>
</font>
</Label>
 
Search WWH ::




Custom Search