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);
}
}
});
Defining a TreeItem
Taking a look at the following snippet from Listing 6-9, you see that each TreeItem is given the value that it represents, and 0 or more children TreeItem objects: animalTree.getChildren().addAll(new TreeItem("Lion"), new TreeItem("Tiger"), new TreeItem("Bear")); TreeItem root = new TreeItem("Root"); root.getChildren().addAll(animalTree, mineralTree, vegetableTree);
In addition, you can set properties such as •graphic, which displays a Node in the TreeItem •expanded, which controls whether the TreeItem is expanded or collapsed
Now that you know how to create a TreeView and its TreeItem instances, let’s examine how to detect when a TreeItem has been selected.
Detecting When a TreeItem Is Selected
To detect when the user selects a TreeItem in the TreeView, the StarterApp program adds a ChangeListener to the selectedItem property of the tree view’s selection model. The code for accomplishing this is shown in this snippet from Listing 6-9:
A TreeView may allow the user to select a single row, or multiple rows, based on its selection mode. In the first line of the preceding snippet, we’re setting the selection mode of the TableView to SINGLE.
In Step 11 of the exercise, when you clicked on a leaf TreeItem in the TreeView, the ListView on the right side of Figure 6-6 was populated. The code in this snippet accomplishes this by first checking to see if the selected TreeItem is a leaf, and then populating the model that backs the ListView.