import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
class JTreeTest
{
JFrame f = new JFrame("JTree的用法");
JScrollPane jsp = new JScrollPane();
JPanel jp = new JPanel(new GridLayout(3,1,5,10));
JLabel l1 = new JLabel("显示节点路径");
JLabel l2 = new JLabel("显示节点索引");
JLabel l3 = new JLabel("显示节点对象");
Font ft = new Font("Serif",Font.BOLD,18);
JTree tr;
void go()
{
DefaultMutableTreeNode root,node1,node11;
f.getContentPane().add(jsp);
f.getContentPane().add("East",jp);
jp.add(l1);jp.add(l2);jp.add(l3);
jp.setBackground(Color.white);
root = new DefaultMutableTreeNode("学校");
root.add(node1 = new DefaultMutableTreeNode("南京师范大学"));
node1.add(node11 = new DefaultMutableTreeNode("数科院"));
node11.add(new DefaultMutableTreeNode("计算机系"));
node11.add(new DefaultMutableTreeNode("软件工程系"));
node11.add(new DefaultMutableTreeNode("数学系"));
node1.add(node11 = new DefaultMutableTreeNode("文学院"));
node11.add(new DefaultMutableTreeNode("古代文学系"));
node11.add(new DefaultMutableTreeNode("现代文学系"));
root.add(node1 = new DefaultMutableTreeNode("东南大学"));
node1.add(node11 = new DefaultMutableTreeNode("建筑学院"));
node11.add(new DefaultMutableTreeNode("设计系"));
node11.add(new DefaultMutableTreeNode("材料系"));
node11.add(new DefaultMutableTreeNode("力学系"));
node1.add(node11 = new DefaultMutableTreeNode("计算机学院"));
node11.add(new DefaultMutableTreeNode("网络系"));
node11.add(new DefaultMutableTreeNode("计算机安全系"));
root.add(node1 = new DefaultMutableTreeNode("海南大学"));
tr = new JTree(root);
tr.setFont(ft);
tr.setShowsRootHandles(true);
jsp.getViewport().add(tr);
l1.setFont(ft);
l2.setFont(ft);
l3.setFont(ft);
f.setSize(400,350);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(true);
f.setVisible(true);
tr.addTreeSelectionListener(new TreeH());
}
public static void main(String[] args)
{
JTreeTest that = new JTreeTest();
that.go();
}
class TreeH implements TreeSelectionListener
{
public void valueChanged(TreeSelectionEvent e)
{
TreePath tp;
int idx;
String str;
DefaultMutableTreeNode dmt;
tp = tr.getSelectionPath();
dmt = (DefaultMutableTreeNode)tr.getLastSelectedPathComponent();
str = (String)dmt.getUserObject();
idx = tr.getRowForPath(tp);
l1.setText(tp.toString());
l2.setText("索引=" +idx);
l3.setText(str);
}
}
}