Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2244474
  • 博文数量: 556
  • 博客积分: 11457
  • 博客等级: 上将
  • 技术积分: 5973
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-24 22:33
文章分类

全部博文(556)

文章存档

2013年(22)

2012年(74)

2011年(460)

分类: Java

2011-07-20 11:10:28

  1. package simpletreetest;
  2. import java.awt.*;
  3. import javax.swing.*;
  4. import javax.swing.tree.*;
  5. import javax.swing.event.*;
  6. import javax.swing.text.AbstractDocument.BranchElement;
  7. public class MyFrame extends JFrame{
  8.     private JTree tree;
  9.     
  10.     public MyFrame(){
  11.         setTree();
  12.         this.add(tree);
  13.         this.setSize(500,300);
  14.     }
  15.     
  16.     public void setTree(){
  17.         DefaultMutableTreeNode lx=new DefaultMutableTreeNode("联系人");
  18.         DefaultMutableTreeNode qr=new DefaultMutableTreeNode("亲人");
  19.         DefaultMutableTreeNode ba=new DefaultMutableTreeNode("爸爸");
  20.         DefaultMutableTreeNode jj=new DefaultMutableTreeNode("姐姐");
  21.         DefaultMutableTreeNode tx=new DefaultMutableTreeNode("同学");
  22.         DefaultMutableTreeNode cy=new DefaultMutableTreeNode("程远");
  23.         DefaultMutableTreeNode py=new DefaultMutableTreeNode("朋友");
  24.         DefaultMutableTreeNode wz=new DefaultMutableTreeNode("武总");
  25.         
  26.         lx.add(qr);
  27.         qr.add(ba);
  28.         qr.add(jj);
  29.         
  30.         lx.add(tx);
  31.         tx.add(cy);
  32.         
  33.         lx.add(py);
  34.         py.add(wz);
  35.         
  36.         tree=new JTree(lx);
  37.         tree.addTreeSelectionListener(new TreeSelectionListener() {

  38.             public void valueChanged(TreeSelectionEvent e) {
  39.                 DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
  40.                 if(node==null) return;
  41.                 if(node.isLeaf()){
  42.                     leaf(node);
  43.                 }else{
  44.                   branch(node);
  45.                 }
  46.                 
  47.             }
  48.         });
  49.     }
  50.        private void leaf(DefaultMutableTreeNode node){
  51.        System.out.println("叶节点:" + node.getUserObject());
  52.        }


  53.        private void branch(DefaultMutableTreeNode node) {
  54.          System.out.println("枝节点:" + node.getUserObject());
  55.        }

  56.         
  57.       public static void main(String[] args) {
  58.          JFrame frame = new MyFrame();
  59.          frame.setVisible(true);
  60. }
  61. }

运行效果:

参考资料:

阅读(15307) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

qu1210happy2013-07-27 15:32:57

你好,请问要实现这样一个功能,导出成文本格式如上,然后再导入又还原成上图,我的导出已经实现,导入这块,挂树没有实现。