Search code examples
javafxtreeviewfxml

TreeView in FXML


How can I create a TreeView in FXML including all the branches and components in it? I can't find documentation about it. There is just code about how to populate it but I want to do it in FXML so y can have the design apart of the logic.


Solution

  • There's no specific documentation for FXML (beyond the Introduction to FXML document): but there is no need for any. An element beginning with an uppercase character is an instruction to instantiate the class of that name, so

    <TreeView></TreeView>
    

    will instantiate a TreeView. Attributes correspond to properties, so if you needed you could do

    <TreeView editable="true"></TreeView>
    

    Nested elements beginning with lower case also correspond to properties, and will be set to the enclosed FXML structure. So you can create a tree view with code like

    <TreeView fx:id = "treeView">
        <root>
            <TreeItem fx:id="rootItem" value="Root" expanded="true">
                <children>
                    <TreeItem fx:id="child1" value="Child 1" expanded="true">
                        <children>
                            <TreeItem fx:id="child11" value="Child 1.1"></TreeItem>
                            <TreeItem fx:id="child12" value="Child 1.2"></TreeItem>
                        </children>
                    </TreeItem>
                    <TreeItem fx:id="child2" value="Child 2">
                        <children>
                            <TreeItem fx:id="child21" value="Child 2.1"></TreeItem>
                            <TreeItem fx:id="child22" value="Child 2.2"></TreeItem>
                        </children>
                    </TreeItem>
                </children>
            </TreeItem>
        </root>
    </TreeView>
    

    You can, of course, see all the properties in the API documentation.