Java JTree_6
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;
public class JTree_6 extends JFrame {
/**
*
*/
private static final long serialVersionUID = -7110119222281494418L;
public JTree_6() {
// TODO Auto-generated constructor stub
DefaultMutableTreeNode root = new DefaultMutableTreeNode("倾城爱家");
DefaultMutableTreeNode nodeA = new DefaultMutableTreeNode("经理办公室");
DefaultMutableTreeNode nodeB = new DefaultMutableTreeNode("人事部");
DefaultMutableTreeNode nodeC = new DefaultMutableTreeNode("技术部");
DefaultMutableTreeNode nodeD = new DefaultMutableTreeNode("服务部");
DefaultMutableTreeNode nodeE = new DefaultMutableTreeNode("推广部");
DefaultMutableTreeNode nodeCA = new DefaultMutableTreeNode("网络维护部");
DefaultMutableTreeNode nodeCB = new DefaultMutableTreeNode("应用开发部");
DefaultMutableTreeNode nodeDA = new DefaultMutableTreeNode("网络服务部");
DefaultMutableTreeNode nodeDB = new DefaultMutableTreeNode("内勤开发部");
root.add(nodeA);
root.add(nodeB);
root.add(nodeC);
root.add(nodeD);
root.add(nodeE);
nodeC.add(nodeCA);
nodeC.add(nodeCB);
nodeD.add(nodeDA);
nodeD.add(nodeDB);
final DefaultTreeModel treeModel = new DefaultTreeModel(root);
final JTree tree = new JTree(treeModel);
Container container = getContentPane();
container.add(tree, BorderLayout.CENTER);
tree.addTreeWillExpandListener(new TreeWillExpandListener() {
@Override
public void treeWillCollapse(TreeExpansionEvent event)
throws ExpandVetoException {
// TODO Auto-generated method stub
TreePath path = event.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
.getLastPathComponent();
System.out.println("节点“" + node.getUserObject() + "”将被折叠!");
}
@Override
public void treeWillExpand(TreeExpansionEvent event)
throws ExpandVetoException {
// TODO Auto-generated method stub
TreePath path = event.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
.getLastPathComponent();
System.out.println("节点“" + node.getUserObject() + "”将被展开!");
}
});
tree.addTreeExpansionListener(new TreeExpansionListener() {
@Override
public void treeCollapsed(TreeExpansionEvent event) {
// TODO Auto-generated method stub
TreePath path = event.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
.getLastPathComponent();
System.out.println("节点“" + node.getUserObject() + "”已经被折叠!");
System.out.println();
}
@Override
public void treeExpande
补充:软件开发 , Java ,