work167.java
package test09;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.WindowConstants;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;
public class work167 extends JFrame
{
public work167()
{
this.setTitle("树节点展开和折叠事件");
this.setLayout(new BorderLayout());
DefaultMutableTreeNode root1 = new DefaultMutableTreeNode("某某企业");
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("经理办公室");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("人事部");
DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("技术部");
DefaultMutableTreeNode node4 = new DefaultMutableTreeNode("服务部");
DefaultMutableTreeNode node5 = new DefaultMutableTreeNode("推广部");
node3.add(new DefaultMutableTreeNode("网络维护部"));
node3.add(new DefaultMutableTreeNode("应用开发部"));
node4.add(new DefaultMutableTreeNode("网络服务部"));
node4.add(new DefaultMutableTreeNode("内勤开发部"));
root1.add(node1);
root1.add(node2);
root1.add(node3);
root1.add(node4);
root1.add(node5);
JTree tree1 = new JTree(root1);
this.getContentPane().add(tree1,BorderLayout.CENTER);
//树节点,展开前
tree1.addTreeWillExpandListener(new TreeWillExpandListener()
{
@Override
public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException
{
TreePath path1 = event.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path1.getLastPathComponent();
System.out.println("节点<" + node + ">将要展开");
}
@Override
public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException
{
TreePath path1 = event.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path1.getLastPathComponent();
System.out.println("节点<" + node + ">将要折叠");
}
});
//树节点,展开时
tree1.addTreeExpansionListener(new TreeExpansionListener()
{
@Override
public void treeExpanded(TreeExpansionEvent event)
{
TreePath path1 = event.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path1.getLastPathComponent();
System.out.println("节点<" + node + ">已经展开");
System.out.println();
}
@Override
public void treeCollapsed(TreeExpansionEvent event)
{
TreePath path1 = event.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path1.getLastPathComponent();
System.out.println("节点<" + node + ">已经折叠");
System.out.println();
}
});
this.setSize(500,500);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
work167 s1 = new work167();
}
}
work168.java