Java JTree Create createTree(JTree jTree1, String[] leaves)

Here you can find the source of createTree(JTree jTree1, String[] leaves)

Description

create Tree

License

Open Source License

Declaration

public static void createTree(JTree jTree1, String[] leaves) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.HashMap;
import java.util.Map;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class Main {
    public static void createTree(JTree jTree1, String[] leaves) {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("", true);
        jTree1.setModel(new DefaultTreeModel(root));
        jTree1.setRootVisible(false);//from ww w .j  av  a  2  s  . c o  m
        DefaultMutableTreeNode currentNode = root;
        Map<String, DefaultMutableTreeNode> pathList = new HashMap<String, DefaultMutableTreeNode>();
        for (int i = 0; i < leaves.length; i++) {

            String[] s = leaves[i].split("/");
            for (int j = 0; j < s.length; j++) {

                DefaultMutableTreeNode node = new DefaultMutableTreeNode(s[j], j != s.length - 1);
                String path = getPath(currentNode.getUserObjectPath()) + getPath(node.getUserObjectPath());
                DefaultMutableTreeNode pathNode = pathList.get(path);

                if (pathNode == null) {
                    pathList.put(path, node);
                    currentNode.add(node);
                } else {
                    node = pathNode;
                }

                currentNode = node;
            }
            currentNode = root;
        }
    }

    public static String getPath(Object[] str) {
        String res = "";
        for (int i = 0; i < str.length; i++) {

            res += str[i].toString() + (i == 0 || i == str.length ? "" : "/");
        }
        return res;
    }
}

Related

  1. createEnumeration(String className, TreeNode root)
  2. createSimpleTreeCellRenderer(ImageIcon icon)
  3. createTree()
  4. createTreeNode(String text, int depth)