import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.tree.*;
class A extends JFrame implements TreeSelectionListener{
JTextArea text=new JTextArea(20,20);
JTree tree=null;
public A(){
super("实验");
Container con=getContentPane(); //定义JFrame窗体容器
DefaultMutableTreeNode root=new DefaultMutableTreeNode("c:\\");
DefaultMutableTreeNode t1=new DefaultMutableTreeNode("备份资料");
DefaultMutableTreeNode t2=new DefaultMutableTreeNode("Java学习");
DefaultMutableTreeNode t1_1=new DefaultMutableTreeNode("思维论坛精华帖子");
DefaultMutableTreeNode t1_2=new DefaultMutableTreeNode("来往邮件");
DefaultMutableTreeNode t2_1=new DefaultMutableTreeNode("视频教程");
DefaultMutableTreeNode t2_2=new DefaultMutableTreeNode("Java3D"); //定义结点
JTree tree=new JTree(root);
root.add(t1);
root.add(t2); //定义root的子结点
t1.add(t1_1);
t1.add(t1_2); //定义t1_1 t1_2为t1的结点
t2.add(t2_1);
t2.add(t2_2); //定义t2_1 t2_2为t2的子结点
JScrollPane s=new JScrollPane(text); //带滚动条的面板(树放置其中)
JSplitPane sp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,tree,s);
con.add(sp);
tree.addTreeSelectionListener(this);
setVisible(true);
setSize(300,300);
validate();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void valueChanged(TreeSelectionEvent e){
if(e.getSource()==tree){ //用来判断发起事件的控件是不是tree
DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent(); //返回最后选定的节点
if(node!=null && node.isLeaf()){
String str=node.toString();
if(str.equals("思维论坛精华帖子")){
text.setText(str);
}
else if(str.equals("来往邮件")){
text.setText(str);
}
else if(str.equals("视频教程")){
text.setText(str);
}
else if(str.equals("Java3D")){
text.setText(str);
}
}
else{
text.setText(node.getUserObject().toString());
}
}
}
}
class B{
public static void main(String[]args){
A a=new A();
}
}