Expansion and Collapse Events in a JTree are fired before a node is expanded or collapsed can be vetoed, thereby preventing the operation. : JTree « Swing « Java Tutorial
public class Main { public static void main() {
JTree tree = new JTree();
tree.addTreeWillExpandListener(new MyTreeWillExpandListener());
tree.addTreeExpansionListener(new MyTreeExpansionListener());
JFrame f = new JFrame();
f.add(new JScrollPane(tree));
f.setSize(300, 300);
f.setVisible(true);
}
}
class MyTreeWillExpandListener implements TreeWillExpandListener { public void treeWillExpand(TreeExpansionEvent evt) throws ExpandVetoException {
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath(); boolean veto = false; if (veto) { throw new ExpandVetoException(evt);
}
}
public void treeWillCollapse(TreeExpansionEvent evt) throws ExpandVetoException {
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath(); boolean veto = false; if (veto) { throw new ExpandVetoException(evt);
}
}
}
class MyTreeExpansionListener implements TreeExpansionListener { public void treeExpanded(TreeExpansionEvent evt) {
JTree tree = (JTree) evt.getSource();