June 12, 2009, 2:33 a.m.
posted by pythonrocks
How to Write a Tree Selection ListenerTo detect when the user selects a node in a tree, you need to register a tree selection listener. Here's an example, taken from the TreeDemo example discussed in Responding to Node Selection (page 440) in Chapter 7, 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 (node == null) return;
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_SELECTIONThis is the default mode for the default tree selection model. With this mode, any combination of nodes can be selected. SINGLE_TREE_SELECTIONThis is the mode used by the preceding example. At most one node can be selected at a time. CONTIGUOUS_TREE_SELECTIONWith this mode, only nodes in adjoining rows can be selected. The Tree Selection Listener APIFigure lists the only method in the TreeSelectionListener interface and Figure describes the methods in the TreeExpansionEvent class. Note that TreeSelectionListener has no corresponding adapter class. Also refer to the TreeSelectionListener API documentation at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/TreeSelectionListener.html. The TreeExpansionEvent API documentation is online at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/TreeExpansionEvent.html.
Examples That Use Tree Selection ListenersThe following examples use tree selection listeners.
|
- Comment