Creating a TreeView

As you experienced in Steps 10 and 11 of the exercise, the TreeView shown in Figure 6-5 contains a hierarchical structure of tree items, each of which may be expanded and collapsed. The code that defines and populates the TreeView in the StarterApp program is shown in Listing 6-9.

Listing 6-9. The createSplitTreeListDemoNode()

Node createSplitTreeListDemoNode() {
    TreeItem animalTree = new TreeItem("Animal");
        animalTree.getChildren().addAll(new TreeItem("Lion"), new TreeItem("Tiger"), new TreeItem("Bear"));
        TreeItem mineralTree = new TreeItem("Mineral");
        mineralTree.getChildren().addAll(new TreeItem("Copper"), new TreeItem("Diamond"), new TreeItem("Quartz"));
        TreeItem vegetableTree = new TreeItem("Vegetable");
        vegetableTree.getChildren().addAll(new TreeItem("Arugula"), new TreeItem("Broccoli"), new TreeItem("Cabbage"));

        TreeItem root = new TreeItem("Root");
        root.getChildren().addAll(animalTree, mineralTree, vegetableTree);
        TreeView treeView = new TreeView(root);
        treeView.setMinWidth(150);
        treeView.setShowRoot(false);
        treeView.setEditable(false);

        ListView listView = new ListView(model.listViewItems);

        SplitPane splitPane = new SplitPane();
        splitPane.getItems().addAll(treeView, listView);

        treeView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        treeView.getSelectionModel().selectedItemProperty()
                .addListener((ObservableValue observable, Object oldValue, Object newValue) -> {
                    TreeItem treeItem = (TreeItem) newValue;
                    if (newValue != null && treeItem.isLeaf()) {
                        model.listViewItems.clear();
                        for (int i = 1; i <= 10000; i++) {
                            model.listViewItems.add(treeItem.getValue() + " " + i);
                        }
                    }
                });

        return splitPane;
}

As shown in the following snippet from Listing 6-9, a TreeView can be supplied with values for several properties, including whether the root TreeItem should show and whether the TreeView is editable. In the StarterApp program we’re also setting the minWidth so that the user can’t hide the TreeView by dragging the SplitPane divider (as you noticed in Step 12 of the previous exercise).

TreeView treeView = new TreeView(root);
treeView.setMinWidth(150);
treeView.setShowRoot(false);
treeView.setEditable(false);
  ...