Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
To detect when the user selects a node in a tree, you need to register a tree selection listener. Here is an example, taken from theTreeDemo
example discussed in Responding to Node Selection, of detecting node selection in a tree that can have at most one node selected at a time:To specify that the tree should support single selection, the program uses this code:tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; Object nodeInfo = node.getUserObject(); ... /* React to the node selection. */ ... } });Thetree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION);TreeSelectionModel
interface defines three values for the selection mode:
DISCONTIGUOUS_TREE_SELECTION
- This is the default mode for the default tree selection model. With this mode, any combination of nodes can be selected.
SINGLE_TREE_SELECTION
- This is the mode used by the preceding example. At most one node can be selected at a time.
CONTIGUOUS_TREE_SELECTION
- With this mode, only nodes in adjoining rows can be selected.
TheTreeSelectionListener
interface contains a single method, and thus has no corresponding adapter class. Here is the loneTreeSelectionListener
method:The
void valueChanged(TreeSelectionEvent)
- Called whenever the selection changes.
valueChanged
method has a single parameter: anTreeSelectionEvent
object. TheTreeSelectionEvent
class defines several methods for returning the path or paths of the selection. As the preceding code example shows, you can also useJTree
methods such asgetLastSelectedPathComponent
to get the current selection.
If you need to find the object that fired the tree selection event, you can use the
getSource
method, whichTableSelectionEvent
inherits fromEventObject
.
TheTreeDemo
example, as well as examples such asTreeIconDemo
that add to it, uses a tree selection listener. The listener responds to node clicks by showing the appropriate HTML document. You can find the source code forTreeDemo
inTreeDemo
, and a full discussion of the program in How to Use Trees.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.