Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
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 the TreeDemo
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:
tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); /* if nothing is selected */ if (node == null) return; /* retrieve the node that was selected */ Object nodeInfo = node.getUserObject(); ... /* React to the node selection. */ ... } });
To specify that the tree should support single selection, the program uses this code:
tree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION);
The TreeSelectionModel
interface defines three values for the selection mode:
DISCONTIGUOUS_TREE_SELECTION
SINGLE_TREE_SELECTION
CONTIGUOUS_TREE_SELECTION
The TreeSelectionListener Interface
Because TreeSelectionListener
has only one method, it has no corresponding adapter class.
方法 | 目的 |
---|---|
valueChanged(TreeSelectionEvent) | Called whenever the selection changes. |
方法 | 目的 |
---|---|
Object getSource() (in java.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() (in JTree ) |
Return the current lead path. |
The following table lists the examples that use tree selection listeners.
例子 | Where Described | Notes |
---|---|---|
TreeDemo |
如何使用树 | The tree listener responds to node clicks by showing the appropriate HTML document. |