Java Reference
In-Depth Information
Each of the methods has a TreeExpansionEvent as its argument. The TreeExpansionEvent
class has a single method for getting the path to the expanded or collapsed node: public
TreePath getPath() .
TreeWillExpandListener Interface and ExpandVetoException
Class
The JTree supports the registration of a TreeWillExpandListener , whose definition follows.
public interface TreeWillExpandListener implements EventListener {
public void treeWillCollapse(TreeExpansionEvent treeExpansionEvent)
throws ExpandVetoException;
public void treeWillExpand(TreeExpansionEvent treeExpansionEvent)
throws ExpandVetoException;
}
The two method signatures are similar to the TreeExpansionListener , and they can throw
an ExpandVetoException . Any registered listener will be notified prior to the expansion or collapse
of a parent node. If the listener doesn't want the expansion or collapse to happen, that listener
can throw the exception to reject the request, stopping the node from opening or closing.
To demonstrate a TreeWillExpandListener , the following code won't permit either the
sports node to be expanded in the default data model or the colors node to be collapsed.
TreeWillExpandListener treeWillExpandListener = new TreeWillExpandListener() {
public void treeWillCollapse(TreeExpansionEvent treeExpansionEvent)
throws ExpandVetoException {
TreePath path = treeExpansionEvent.getPath();
DefaultMutableTreeNode node =
(DefaultMutableTreeNode)path.getLastPathComponent();
String data = node.getUserObject().toString();
if (data.equals("colors")) {
throw new ExpandVetoException(treeExpansionEvent);
}
}
public void treeWillExpand(TreeExpansionEvent treeExpansionEvent)
throws ExpandVetoException {
TreePath path = treeExpansionEvent.getPath();
DefaultMutableTreeNode node =
(DefaultMutableTreeNode)path.getLastPathComponent();
String data = node.getUserObject().toString();
if (data.equals("sports")) {
throw new ExpandVetoException(treeExpansionEvent);
}
}
};
Don't forget to add the listener to a tree with a line of code similar to the following:
tree.addTreeWillExpandListener(treeWillExpandListener)
Search WWH ::




Custom Search