Java Reference
In-Depth Information
TreeSelectionModel selectionModel = tree.getSelectionModel();
selectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
If you're interested in finding out the selected path (or paths), you can ask the
JTree
directly. You don't need to get the selected path from the model.
TreeSelectionListener Interface and TreeSelectionEvent Class
When the set of selected nodes within a tree changes, a
TreeSelectionEvent
is generated
and any registered
TreeSelectionListener
objects of the
TreeSelectionModel
are notified.
The
TreeSelectionListener
can be registered either with the
JTree
or directly with the
TreeSelectionModel
. The interface definition follows.
public interface TreeSelectionListener implements EventListener {
public void valueChanged(TreeSelectionEvent treeSelectionEvent);
}
TreePath Class
The last major class to examine is
TreePath
. It has been used in many of the earlier examples in
this chapter. It describes a read-only collection of nodes that map a path from the root node to
another node, where the root could be the top of a
subtree
versus the root of the whole tree.
Although two constructors exist to create
TreePath
objects, you'll normally deal with them only
as the return value from a method. You can also create a new path by adding an element to an
existing
TreePath
with
public TreePath pathByAddingChild(Object child)
.
A
TreePath
can be thought of as an
Object
array, in which the first element of the array is
the root of the tree and the last element is called the
last path component
. In between are all the
components connecting them. Normally, the elements of the array will be of type
TreeNode
.
However, because
TreeModel
supports objects of any type, the
path
property of
TreePath
is
defined to be an array of
Object
nodes. Table 17-7 lists the four
TreePath
properties.
Table 17-7.
TreePath Properties
Property Name
Data Type
Access
lastPathComponent
Object
Read-only
parentPath
TreePath
Read-only
path
Object[ ]
Read-only
pathCount
int
Read-only
To better understand
TreePath
, let's reuse the tree traversal sample tree from Figure 17-18,
shown once more in Figure 17-20.