The Java TM Tutorial

| 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, 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 (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` 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` 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`.

### 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.

| Start of Tutorial > Start of Trail > Start of Lesson | Search