| |
15. 36. 2. To find out when a tree node has been expanded or collapsed: TreeExpansionListener Interface and TreeExpansionEvent Class |
|
public interface TreeExpansionListener implements EventListener {
public void treeCollapse(TreeExpansionEvent treeExpansionEvent);
public void treeExpand(TreeExpansionEvent treeExpansionEvent);
}
|
|
import java.awt.BorderLayout;
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.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
public class TreeExpansionListenerDemo {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
root.add(new DefaultMutableTreeNode("A"));
root.add(new DefaultMutableTreeNode("B"));
root.add(new DefaultMutableTreeNode("C"));
JTree tree = new JTree(root);
TreeExpansionListener treeExpandListener = new TreeExpansionListener() {
public void treeExpanded(TreeExpansionEvent event) {
TreePath path = event.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
String data = node.getUserObject().toString();
System.out.println("Expanded: " + data);
}
public void treeCollapsed(TreeExpansionEvent event) {
TreePath path = event.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
String data = node.getUserObject().toString();
System.out.println("Collapsed: " + data);
}
};
tree.addTreeExpansionListener(treeExpandListener);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
|
|
15. 36. 树已扩展事件监听 | | 15. 36. 1. | 如何撰写树扩张事件监听 | | | | 15. 36. 2. | To find out when a tree node has been expanded or collapsed: TreeExpansionListener Interface and TreeExpansionEvent Class | | |
|