Java Reference
In-Depth Information
The preceding attribute declares that
StageCoach.fxml
will work together with the Java class
projavafx.
stagecoach.ui.StageCoachController
. The
fx:id
attribute can appear in every element that represents a JavaFX
Node
. The value of
fx:id
is the name of a field in the controller that represents the
Node
after the FXML file has been
loaded. The
StageCoach.fxml
file declares the following
fx:ids
(only lines with
fx:id
attribute are shown):
<Group fx:id="rootGroup"
<Rectangle fx:id="blue"
<VBox fx:id="contentBox"
<Text fx:id="textStageX"
<Text fx:id="textStageY"
<Text fx:id="textStageH"
<Text fx:id="textStageW"
<Text fx:id="textStageF"
<CheckBox fx:id="checkBoxResizable"
<CheckBox fx:id="checkBoxFullScreen"
<HBox fx:id="titleBox">
<Label fx:id="titleLabel"
<TextField fx:id="titleTextField"
<Button fx:id="toBackButton"
<Button fx:id="toFrontButton"
<Button fx:id="closeButton"
Thus after the
FXMLLoader
is done loading the FXML file, the top-level
Group
node in the FXML file can be
accessed and manipulated in Java code as the
rootGroup
field of the
StageCoachController
class. In this FXML
file, we assigned an
fx:id
to all the nodes that we create. This is done for illustration purposes only. If there is no
reason to manipulate a node programmatically, such as is the case for a static label, both the
fx:id
attribute and the
corresponding field in the controller can be omitted.
Providing programmatic access to the nodes in an FXML file is one role that the controller plays. Another role the
controller plays is to provide the methods that handle user input and interaction events originating from the nodes in
an FXML file. These event handlers are specified by attributes whose name begins with “
on
”, such as
onMouseDragged
,
onMousePressed
, and
onAction
. They correspond to the
setOnMouseDragged()
,
setOnMousePressed()
, and
setOnAction()
methods in the
Node
classes or its subclasses. To set the event handlers to a method in the controller,
use the method name preceded with a “
#
” character as the value of the
onMouseDragged
,
onMousePressed
, and
onAction
attributes. The
StageCoach.fxml
file declares the following event handlers (only lines with event handlers
are shown):
<Group fx:id="rootGroup"
onMouseDragged="#mouseDraggedHandler"
onMousePressed="#mousePressedHandler"
<Button fx:id="toBackButton"
onAction="#toBackEventHandler"
<Button fx:id="toFrontButton"
onAction="#toFrontEventHandler"
<Button fx:id="closeButton"
onAction="#closeEventHandler"
The event handler methods in the controller class should in general conform to the signature of the single
method in the
EventHandler<T>
interface
void handle(T event)
Search WWH ::
Custom Search