JTree 的使用

http://dhc027.blog.163.com/blog/static/17329508520109292151515/?COLLCC=3009409691&

 

 

一、JTree用法及JTree使用经验总结
××××××××××××××××××××××××××××××××××××××××××××××
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

/*
JTree的构造函数:
JTree()
JTree(Hashtable value)
JTree(Object[] value)// 只有这个构造函数可以创建多个根结点
JTree(TreeModel newModel)
JTree(TreeNode root)
JTree(TreeNode root, boolean asksAllowsChildren)
JTree(Vector value)
*/
public class JTreeDemo {
public static void main(String[] args) {
   // 构造函数:JTree()
   JTree example1 = new JTree();
   // 构造函数:JTree(Object[] value)
   Object[] letters = { " a ", " b ", " c ", " d ", " e " };
   JTree example2 = new JTree(letters);

   // 构造函数:JTree(TreeNode root)(TreeNode空)
   // 用空结点创建树
   DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(); // 定义树结点
   JTree example3 = new JTree(node1); // 用此树结点做参数调用 JTree的构造函数创建含有一个根结点的树

   // 构造函数:JTree(TreeNode root)(同上,只是TreeNode非空)
   // 用一个根结点创建树
   DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(" Color ");
   // 结点不可以颜色,默认为白面黑字
   JTree example4 = new JTree(node2);
   example4.setBackground(Color.lightGray);

   // 构造函数:JTree(TreeNode root, boolean
   // asksAllowsChildren)(同上,只是TreeNode又有不同)
   // 使用DefaultMutableTreeNode类先用一个根结点创建树,设置为可添加孩子结点,再添加孩子结点
   DefaultMutableTreeNode color = new DefaultMutableTreeNode(" Color ", true);
   DefaultMutableTreeNode gray = new DefaultMutableTreeNode(" Gray ");
   color.add(gray);
   color.add(new DefaultMutableTreeNode(" Red "));
   gray.add(new DefaultMutableTreeNode(" Lightgray "));
   gray.add(new DefaultMutableTreeNode(" Darkgray "));
   color.add(new DefaultMutableTreeNode(" Green "));
   JTree example5 = new JTree(color);

   // 构造函数:JTree(TreeNode root)(同上,只是TreeNode非空)
   // 通过逐个添加结点创建树
   DefaultMutableTreeNode biology = new DefaultMutableTreeNode(" Biology ");
   DefaultMutableTreeNode animal = new DefaultMutableTreeNode(" Animal ");
   DefaultMutableTreeNode mammal = new DefaultMutableTreeNode(" Mammal ");
   DefaultMutableTreeNode horse = new DefaultMutableTreeNode(" Horse ");
   mammal.add(horse);
   animal.add(mammal);
   biology.add(animal);
   JTree example6 = new JTree(biology);
   horse.isLeaf();
   horse.isRoot();

   // 构造函数:JTree(TreeModel newModel)
   // 用DefaultMutableTreeNodel类定义一个结点再用这个结点做参数定义一个用DefaultTreeMode
   // 创建一个树的模型,再用JTree的构造函数创建一个树
   DefaultMutableTreeNode root = new DefaultMutableTreeNode(" Root1 ");
   DefaultMutableTreeNode child1 = new DefaultMutableTreeNode(" Child1 ");
   DefaultMutableTreeNode child11 = new DefaultMutableTreeNode(" Child11 ");
   DefaultMutableTreeNode child111 = new DefaultMutableTreeNode(" Child111 ");
   root.add(child1);
   child1.add(child11);
   child11.add(child111);
   DefaultTreeModel model = new DefaultTreeModel(root);

   JTree example7 = new JTree(model);
   JPanel panel = new JPanel();
   panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
   panel.setPreferredSize(new Dimension(700, 400));
   panel.add(new JScrollPane(example1)); // JTree必须放在JScrollPane上
   panel.add(new JScrollPane(example2));
   panel.add(new JScrollPane(example3));
   panel.add(new JScrollPane(example4));
   panel.add(new JScrollPane(example5));
   panel.add(new JScrollPane(example6));
   panel.add(new JScrollPane(example7));

   JFrame frame = new JFrame(" JTreeDemo ");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setContentPane(panel);
   frame.pack();
   frame.show();
}
}
×××××××××××××××××××××××××××××××××××××××××××××× 

// 数组件申明
private JTree jtNetDevice;
// 滚动面板申明
private JScrollPane jspTree;

1、初始化
     DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root");
     jtNetDevice = new JTree(rootNode);
     jtNetDevice.setAutoscrolls(true);
     getTreeSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);// 设置单选模式
     jspTree = new JScrollPane();
     jspTree.getViewport().add(jtNetDevice, null);

2、三个经常使用的取值函数
   private DefaultTreeModel getTreeModel(){
     return (DefaultTreeModel)jtNetDevice.getModel();
   }
   private DefaultMutableTreeNode getRootNode(){
     return (DefaultMutableTreeNode)getTreeModel().getRoot();
   }
   private TreeSelectionModel getTreeSelectionModel(){
     return jtNetDevice.getSelectionModel();
   }

3、根据node得到path:
   TreePath visiblePath = new TreePath(getTreeModel().getPathToRoot(node));

4、根据Path展开到该节点
   jtNetDevice.makeVisible(visiblePath);

5、根据path设定该节点选定
   jtNetDevice.setSelectionPath(visiblePath);

6、选中节点的方法
   首先,根据节点得到树路径,其中chosen为需要选中的节点
   TreePath visiblePath = new TreePath( ( (DefaultTreeModel) jtNetDevice.getModel()).getPathToRoot(chosen));
   然后根据Path选中该节点
   jtNetDevice.setSelectionPath(visiblePath);

7、滚动到可见位置
   jtNetDevice.scrollPathToVisible(visiblePath);

8、给JTree添加右键弹出菜单
   void jtNetDevice_mouseReleased(MouseEvent e) {
     if (e.isPopupTrigger()) {
       jPopupMenu1.show(e.getComponent(), e.getX(), e.getY());//弹出右键菜单
     }
   }

9、关于JTree的展开
    // If expand is true, expands all nodes in the tree.
    // Otherwise, collapses all nodes in the tree.
    public void expandAll(JTree tree, boolean expand) {
        TreeNode root = (TreeNode)tree.getModel().getRoot();
        // Traverse tree from root
        expandAll(tree, new TreePath(root), expand);
    }
    private void expandAll(JTree tree, TreePath parent, boolean expand) {
        // Traverse children
        TreeNode node = (TreeNode)parent.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            for (Enumeration e=node.children(); e.hasMoreElements(); ) {
                TreeNode n = (TreeNode)e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                expandAll(tree, path, expand);
            }
        }
        // Expansion or collapse must be done bottom-up
        if (expand) {
            tree.expandPath(parent);
        } else {
            tree.collapsePath(parent);
        }
    }

10、如何遍历JTree
    // 创建树
    JTree tree = new JTree();
    // 添加树节点......
    // 遍历所有节点
    visitAllNodes(tree);
    // 仅遍历展开的节点
    visitAllExpandedNodes(tree);
    // Traverse all nodes in tree
    public void visitAllNodes(JTree tree) {
        TreeNode root = (TreeNode)tree.getModel().getRoot();
        visitAllNodes(root);
    }
    public void visitAllNodes(TreeNode node) {
        // node is visited exactly once
        process(node);
        if (node.getChildCount() >= 0) {
            for (Enumeration e=node.children(); e.hasMoreElements(); ) {
                TreeNode n = (TreeNode)e.nextElement();
                visitAllNodes(n);
            }
        }
    }
    // Traverse all expanded nodes in tree
    public void visitAllExpandedNodes(JTree tree) {
        TreeNode root = (TreeNode)tree.getModel().getRoot();
        visitAllExpandedNodes(tree, new TreePath(root));
    }
    public void visitAllExpandedNodes(JTree tree, TreePath parent) {
        // Return if node is not expanded
        if (!tree.isVisible(parent)) {
            return;
        }
        // node is visible and is visited exactly once
        TreeNode node = (TreeNode)parent.getLastPathComponent();
        process(node);
        // Visit all children
        if (node.getChildCount() >= 0) {
            for (Enumeration e=node.children(); e.hasMoreElements(); ) {
                TreeNode n = (TreeNode)e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                visitAllExpandedNodes(tree, path);
            }
        }
    }

二、Swing组件---JTree
××××××××××××××××××××××××××××××××××××××××××××××
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class JTreeDemo {
public static void main(String[] args) {

   // 构造函数:JTree()
   JTree example1 = new JTree();

   // 构造函数:JTree(Object[] value)
   Object[] letters = { "a", "b", "c", "d", "e" };
   JTree example2 = new JTree(letters);

   // 构造函数:JTree(TreeNode root)(TreeNode空)
   // 用空结点创建树
   DefaultMutableTreeNode node1 = new DefaultMutableTreeNode();// 定义树结点
   JTree example3 = new JTree(node1);// 用此树结点做参数调用 JTree的构造函数创建含有一个根结点的树

   // 构造函数:JTree(TreeNode root)(同上,只是TreeNode非空)
   // 用一个根结点创建树
   DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Color");
   JTree example4 = new JTree(node2);// 结点不可以颜色,默认为白面黑字
   example4.setBackground(Color.lightGray);

   // 构造函数:JTree(TreeNode root, boolean
   // asksAllowsChildren)(同上,只是TreeNode又有不同)
   // 使用DefaultMutableTreeNode类先用一个根结点创建树,设置为可添加孩子结点,再添加孩子结点
   DefaultMutableTreeNode color = new DefaultMutableTreeNode("Color", true);
   DefaultMutableTreeNode gray = new DefaultMutableTreeNode("Gray");
   color.add(gray);
   color.add(new DefaultMutableTreeNode("Red"));
   gray.add(new DefaultMutableTreeNode("Lightgray"));
   gray.add(new DefaultMutableTreeNode("Darkgray"));
   color.add(new DefaultMutableTreeNode("Green"));
   JTree example5 = new JTree(color);

   // 构造函数:JTree(TreeNode root)(同上,只是TreeNode非空)
   // 通过逐个添加结点创建树
   DefaultMutableTreeNode biology = new DefaultMutableTreeNode("Biology");
   DefaultMutableTreeNode animal = new DefaultMutableTreeNode("Animal");
   DefaultMutableTreeNode mammal = new DefaultMutableTreeNode("Mammal");
   DefaultMutableTreeNode horse = new DefaultMutableTreeNode("Horse");
   mammal.add(horse);
   animal.add(mammal);
   biology.add(animal);
   JTree example6 = new JTree(biology);
   horse.isLeaf();// if this node allows children.
   horse.isRoot();// true if this node is the root of its tree

   // 构造函数:JTree(TreeModel newModel)
   // 用DefaultMutableTreeNodel类定义一个结点再用这个结点做参数定义一个用DefaultTreeMode
   // 创建一个树的模型,再用JTree的构造函数创建一个树

   DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root1");
   DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child1");
   DefaultMutableTreeNode child11 = new DefaultMutableTreeNode("Child11");
   DefaultMutableTreeNode child111 = new DefaultMutableTreeNode("Child111");
   DefaultMutableTreeNode child1111 = new DefaultMutableTreeNode(
     "Child1111");
   root.add(child1);
   child1.add(child11);
   child11.add(child111);
   child111.add(child1111);

   DefaultTreeModel model = new DefaultTreeModel(root);

   JTree example7 = new JTree(model);

   JPanel panel = new JPanel();
   panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
   panel.setPreferredSize(new Dimension(700, 400));
   panel.add(new JScrollPane(example1));// JTree必须放在JScrollPane上
   panel.add(new JScrollPane(example2));
   panel.add(new JScrollPane(example3));
   panel.add(new JScrollPane(example4));
   panel.add(new JScrollPane(example5));
   panel.add(new JScrollPane(example6));
   panel.add(new JScrollPane(example7));

   JFrame frame = new JFrame("JTreeDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setContentPane(panel);
   frame.pack();
   frame.show();
}
}
××××××××××××××××××××××××××××××××××××××××××××××

JTree遍历
Enumeration   e   =   root.breadthFirstEnumeration();  
  while(e.hasMoreElements())  
  {  
  DefaultMutableTreeNode   node   =   (DefaultMutableTreeNode)e.nextElement();  
  if(node.getUserObject().equals(obj))return   node;  
  }

展开指定节点  
  public   void   expandTreeNode(JTree   aTree,   DefaultMutableTreeNode   aNode)   {  
          if   (aNode.isLeaf())   {  
              return;  
          }  
          aTree.expandPath(new   TreePath(   (   (DefaultMutableTreeNode)   aNode).getPath()));  
          int   n   =   aNode.getChildCount();  
          for   (int   i   =   0;   i   <   n;   i++)   {  
              expandTreeNode(aTree,   (DefaultMutableTreeNode)   aNode.getChildAt(i));  
          }  
      }

折叠指定节点及其所有子节点  
  public   void   collapseTreeNode(JTree   aTree,   DefaultMutableTreeNode   aNode)   {  
          if   (aNode.isLeaf())   {  
              return;  
          }  
          aTree.collapsePath(new   TreePath(   (   (DefaultMutableTreeNode)   aNode).getPath()));  
          int   n   =   aNode.getChildCount();  
          for   (int   i   =   0;   i   <   n;   i++)   {  
              collapseTreeNode(aTree,   (DefaultMutableTreeNode)   aNode.getChildAt(i));  
          }  
      }

你可能感兴趣的:(JTree)