The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Creating a GUI with JFC/Swing
Lesson: Writing Event Listeners

How to Write a Tree Selection Listener

To detect when the user selects a node in a tree(in the Creating a User Interface trail), you need to register a tree selection listener. Here is an example, taken from the TreeDemo example discussed in Responding to Node Selection(in the Creating a User Interface trail), 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_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 Tree Selection Event API

The TreeSelectionListener(in the API reference documentation) interface contains a single method, and thus has no corresponding adapter class. Here is the lone TreeSelectionListener method:
void valueChanged(TreeSelectionEvent)
Called whenever the selection changes.
The valueChanged method has a single parameter: an TreeSelectionEvent(in the API reference documentation) object. The TreeSelectionEvent class defines several methods for returning the path or paths of the selection. As the preceding code example shows, you can also use JTree methods such as getLastSelectedPathComponent to get the current selection.

If you need to find the object that fired the tree selection event, you can use the getSource method, which TableSelectionEvent inherits from EventObject(in the API reference documentation).

Examples that Use Tree Selection Listeners

The TreeDemo example, as well as examples such as TreeIconDemo 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 for TreeDemo in TreeDemo, and a full discussion of the program in How to Use Trees(in the Creating a User Interface trail).

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search