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:[PENDING: Update this code snippet after example has been modified to remove the inner class.]
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.
The TreeSelectionListener Interface
Because
TreeSelectionListener
has only one method, it has no corresponding adapter class.
Method Purpose valueChanged(TreeSelectionEvent)
Called whenever the selection changes.
Method Purpose Object getSource()
(injava.util.EventObject
)Return the object that fired the event. TreePath getNewLeadSelectionPath()
Return the current lead path. TreePath getOldLeadSelectionPath()
Return the path that was previously the lead path. TreePath getPath()
Return the first path element. TreePath[] getPaths()
Return the paths that have been added or removed from the selection. boolean isAddedPath()
Return true if the first path element has been added to the selection. Returns false if the first path has been removed from the selection. boolean isAddedPath(int)
Return true if the path specified by the index was added to the selection. boolean isAddedPath(TreePath)
Return true if the specified path was added to the selection. Object getLastSelectedPathComponent()
Return the last path component in the first node of the current selection. TreePath getLeadSelectionPath()
(inJTree
)Return the current lead path.
The following table lists the examples that use tree selection listeners.
Example Where Described Notes TreeDemo
[PENDING: When this example has been updated to 1.4, this link will point to it.]How to Use Trees The tree listener responds to node clicks by showing the appropriate HTML document.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.