1. How to Write a Tree Expansion Listener

Sometimes when using a tree, you might need to react when a branch becomes expanded or collapsed. For example, you might need to load or save data.
Two kinds of listeners report expansion and collapse occurrences: tree expansion listeners and tree-will-expand listeners. This page discusses tree expansionlisteners. See How to Write a Tree-Will-Expand Listener for a description of Tree-Will-Expand listeners.
A tree expansion listener detects when an expansion or collapse has already occured. In general, you should implement a tree expansion listener unless you need to prevent an expansion or collapse from ocurring .
This example demonstrates a simple tree expansion listener. The text area at the bottom of the window displays a message every time a tree expansion event occurs. It's a straightforward, simple demo. To see a more interesting version that can veto expansions, see How to Write a Tree-Will-Expand Listener.


Try this:
  1. Click the Launch button to run TreeExpandEventDemo using Java™ Web Start (download JDK 6). Alternatively, to compile and run the example yourself, consult the example index.
    Launches the TreeExpandEventDemo example
  2. Expand a node. A tree-expanded event is fired.
  3. Collapse the node. A tree-collapsed event is fired.

The following code shows how the program handles expansion events. You can find the source code for this example in TreeExpandEventDemo.java.
public class TreeExpandEventDemo ... {
    ...
    void saySomething(String eventDescription, TreeExpansionEvent e) {
        textArea.append(eventDescription + "; "
                        + "path = " + e.getPath()
                        + newline);
    }

    class DemoArea ... implements TreeExpansionListener {
        ...
        public DemoArea() {
            ...
            tree.addTreeExpansionListener(this);
            ...
        }
        ...
        // Required by TreeExpansionListener interface.
        public void treeExpanded(TreeExpansionEvent e) {
            saySomething("Tree-expanded event detected", e);
        }

        // Required by TreeExpansionListener interface.
        public void treeCollapsed(TreeExpansionEvent e) {
            saySomething("Tree-collapsed event detected", e);
        }
    }
}

The Tree Expansion Listener API

TreeExpansionListener has no adapter class.
MethodPurpose
treeCollapsed(TreeExpansionEvent)Called just after a tree node collapses.
treeExpanded(TreeExpansionEvent)Called just after a tree node expands.

MethodPurpose
Object getSource()Return the object that fired the event.
TreePath getPath()Returns a TreePath object that identifies each node from the root of the tree to the collapsed/expanded node, inclusive.

Examples that Use Tree Expansion Listeners

The following table lists the examples that use tree expansion listeners.
ExampleWhere DescribedNotes
TreeExpandEventDemoThis sectionDisplays a message whenever a tree expansion event occurs.
TreeExpandEventDemo2How to Write a Tree-Will-Expand ListenerAdds a tree-will-expand listener to TreeExpandEventDemo.

2. How to Write a Tree-Will-Expand Listener

The tree-will-expand listener prevents a tree node from expanding or collapsing. To be notified just after an expansion or collapse occurs, you should use a tree expansion listener instead.
This demo adds a tree-will-expand listener to the TreeExpandEventDemo example discussed in How to Write a Tree Expansion Listener. The code added here demonstrates that tree-will-expand listeners prevent node expansions and collapses: The listener will prompt you for confirmation each time you try to expand a node.
Try this: 
  1. Click the Launch button to run TreeExpandEventDemo2 using Java™ Web Start (download JDK 6). Alternatively, to compile and run the example yourself, consult the example index.
    Launches the TreeExpandEventDemo2 example
  2. Click the graphic to the left of the Potrero Hill node. This tells the tree that you want to expand the node. 
    A dialog appears asking you whether you really want to expand the node.
  3. Click "Expand" or dismiss the dialog. 
    Messages in the text area tell you that both a tree-will-expand event and a tree-expanded event have occurred. At the end of each message is the path to the expanded node.
  4. Try to expand another node, but this time press the "Cancel Expansion" button in the dialog. 
    The node does not expand. Messages in the text area tell you that a tree-will-expand event occurred, and that you cancelled a tree expansion.
  5. Collapse the Potrero Hill node. 
    The node collapses without a dialog appearing, because the event handler's treeWillCollapse method lets the collapse occur, uncontested.

The following snippet shows the code that this program adds to TreeExpandEventDemo. The bold line prevents the tree expansion from happening. You can find all the demo's source code in TreeExpandEventDemo2.java.
public class TreeExpandEventDemo2 ... {
    ...
    class DemoArea ... implements ... TreeWillExpandListener {
        ...
        public DemoArea() {
            ...
            tree.addTreeWillExpandListener(this);
            ...
        }
        ...
        //Required by TreeWillExpandListener interface.
        public void treeWillExpand(TreeExpansionEvent e) 
                    throws ExpandVetoException {
            saySomething("Tree-will-expand event detected", e);
            //...show a dialog...
            if (/* user said to cancel the expansion */) {
                //Cancel expansion.
                saySomething("Tree expansion cancelled", e);
                throw new ExpandVetoException(e);
            }
        }

        //Required by TreeWillExpandListener interface.
        public void treeWillCollapse(TreeExpansionEvent e) {
            saySomething("Tree-will-collapse event detected", e);
        }
        ...
    }
}

The Tree-Will-Expand Listener API

TreeWillExpandListener has no adapter class.
MethodPurpose
treeWillCollapse(TreeExpansionEvent)Called just before a tree node collapses. To prevent the collapse from occurring, your implementation of this method should throw a ExpandVetoException event.
treeWillExpand(TreeExpansionEvent)Called just before a tree node expands. To prevent the expansion from occurring, your implementation of this method should throw a ExpandVetoException event.

See The Tree Expansion Event API for information about the TreeExpansionEvent argument for the preceding methods.


Examples that Use Tree-Will-Expand Listeners

TreeExpandEventDemo2, featured in this section, is our only example that uses a tree-will-expand listener.

3. 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 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
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 Listener API

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()
(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.


Examples that Use Tree Selection Listeners

The following table lists the examples that use tree selection listeners.
Example Where Described Notes
TreeDemo How to Use Trees The tree listener responds to node clicks by showing the appropriate HTML document.