Search code examples
javajavafxnodesfxml

What is a "Node" in JavaFx/FXML?


What is meant by the word "Node" within context of JavaFx/FXML? If I search for this question, all I find are people using the term discussing something else, but no explanation. For example, this answer to the question: How do I open the JavaFX FileChooser from a controller class?:

For any node in your scene (for example, the root node; but any node you have injected with @FXML will do), do

chooser.showOpenDialog(node.getScene().getWindow());

What would the node be, and how for that matter would I "inject it with @FXML"?


Solution

  • A Node is the abstract superclass of the graphical elements the scenegraph are "made of".

    Some examples of classes inheriting from Node:

    • TextField
    • AnchorPane
    • Canvas
    • Group
    • VBox
    • Button
    • Label
    • ...

    Injecting a Node with the FXMLLoader id done this way:

    1. Create a field in the controller associated with the fxml with a appropriate type (i.e. any type the element you want to inject can be assigned to). This field must be accessible by the FXMLLoader which means it has to be public or annotated with the @FXML annotation.
    2. Add the id attribute from the fxml namespace (most likely using the prefix fx) to the element in the fxml file that should be injected. The value of that attribute is the name of the field in the controller.

    Example

    fxml

    ....
    <TextField fx:id="myTextField" ....>
    ....
    

    Controller

    ....
    @FXML
    private TextField myTextField;
    ....
    

    The FXMLLoader uses this information to assign the object it creates for that fxml element to the field before the controller's initialize method is called.

    A full example/extendend tutorial including injection can be can be found here: https://docs.oracle.com/javase/8/javafx/fxml-tutorial/fxml_tutorial_intermediate.htm#JFXMG153