Java JTree Path getTree(List paths)

Here you can find the source of getTree(List paths)

Description

constract tree from list of paths.

License

Open Source License

Parameter

Parameter Description
paths the paths

Return

the tree

Declaration

public static TreeNode getTree(List<TreePath> paths) 

Method Source Code

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

import java.util.LinkedHashMap;

import java.util.List;
import java.util.Map;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class Main {
    /**//w w w  . ja  v  a2  s  . c o m
     * constract tree from list of paths.
     *
     * @param paths the paths
     * @return the tree
     */
    public static TreeNode getTree(List<TreePath> paths) {
        return getTree(paths, null);
    }

    /**
     * constract tree from list of paths.
     *
     * @param paths the paths
     * @param root the root
     * @return the tree
     */
    public static TreeNode getTree(List<TreePath> paths, String root) {
        // check for empty list
        if (paths == null || paths.isEmpty())
            return null; //new DefaultMutableTreeNode("EMPTY");

        // iterate over paths
        Map<String, DefaultMutableTreeNode> map = new LinkedHashMap<String, DefaultMutableTreeNode>();
        for (TreePath path : paths) {
            DefaultMutableTreeNode parent = null;
            for (Object n : path.getPath()) {
                DefaultMutableTreeNode node = map.get("" + n);
                if (node == null) {
                    node = new DefaultMutableTreeNode("" + n);
                    map.put("" + n, node);
                }
                // add as child to parent
                if (parent != null)
                    parent.add(node);
                parent = node;
            }
        }
        // the root should be the very first entry in linked table
        return (map.containsKey(root)) ? map.get(root) : map.get(map
                .keySet().iterator().next());
    }
}

Related

  1. getPath(TreeNode treeNode)
  2. getPath(TreeNode treeNode)
  3. getPath(TreeNode treeNode)
  4. getPath(TreeNode treeNode)
  5. getPathStr(TreeNode[] projectNodes)
  6. getTreePath(TreeNode treeNode)
  7. getTreePath(TreeNode treeNode)
  8. getTreePath(TreePath path, JTree tree, boolean compareOnlyLabels)
  9. getTreePathString(TreePath path)