| |
14. 66. 24. Expansion and Collapse Events in a JTree are fired before a node is expanded or collapsed can be vetoed, thereby preventing the operation. |
|
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;
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();
TreePath path = evt.getPath();
System.out.println("treeExpanded");
}
public void treeCollapsed(TreeExpansionEvent evt) {
JTree tree = (JTree) evt.getSource();
TreePath path = evt.getPath();
System.out.println("treeCollapsed");
}
}
|
|
|