JTree的简单使用实例

/**
 *
 */

package JavaGUI;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.tree.*;
import javax.swing.*;
/**
 * @author:FlyingFire
 * @date:2011-6-18
 * @time:10:40:25
 */

public class JTreeTest extends JFrame{

 /**
  * JTree 测试用例
  */
 //显示界面
 public void showFrame(){
  this.setTitle("JTree测试用例");
  this.setSize(400,400);
  this.add(createTree());
  this.setResizable(false);
  this.setLayout(new java.awt.FlowLayout());
  this.setLocationRelativeTo(null);
  this.setDefaultCloseOperation(3);
  this.setVisible(true);
 }
 //创建JPopupMenu对象,并将其返回
 public JPopupMenu createPM(){
  JPopupMenu pm=new JPopupMenu();
     JMenuItem item1=new JMenuItem ("打开");
     JMenuItem item2=new JMenuItem("保存");
     JMenuItem item3=new JMenuItem("退出");
     pm.add(item1);
     pm.add(item2);
     pm.add(item3);
    
     item1.setActionCommand("open");
     item2.setActionCommand("save");
     item3.setActionCommand("exit");
    
        return pm;
 }
 //创建树对象
 public JTree createTree(){
  //创建对象
  JTree tree=new JTree();
  //
  DefaultMutableTreeNode rootNode=new DefaultMutableTreeNode();
  //创建根节点的对象
  rootNode.setUserObject("根节点");
  //创建根节点下的分组节点
  for(int i=0;i<5;i++){
   DefaultMutableTreeNode teamNode=new DefaultMutableTreeNode();
      teamNode.setUserObject("第"+i+"根树枝");
      for(int j=0;j<6;j++){
       DefaultMutableTreeNode leafNode=new DefaultMutableTreeNode();
       leafNode.setUserObject("第"+j+"片叶子");
          teamNode.add(leafNode);
         
      }
      rootNode.add(teamNode);
  }
  //设定默认的树结构模式
  DefaultTreeModel model=new DefaultTreeModel(rootNode);
        tree.setModel(model);
  javax.swing.ImageIcon icon=new ImageIcon("src\\images\\leaf.png");
  DefaultTreeCellRenderer renderer=new DefaultTreeCellRenderer();
  //设定叶节点的图标
  renderer.setLeafIcon(icon);
  //设定分组被收起后的图标
  renderer.setClosedIcon(icon);
  //设定分组展开时的图标
        renderer.setOpenIcon(icon);
        //设定被选项的边缘框的颜色
  renderer.setBorderSelectionColor(Color.red);
  //将renderer对象对JTree所做的各种修饰效果添加到界面
  tree.setCellRenderer(renderer);
  return tree;
 }
 public static void main(String[] args) {
  JTreeTest jtt=new JTreeTest();
  jtt.showFrame();

 }

}

 

你可能感兴趣的:(JTree)