Search code examples
javaswingjtree

Java - JTree not following Path hierarchy


I need to create a tree node that uses a HashMap to build a tree of files, the key of the HashMap is the Path and it's Value is the File Name. I've implemented a code that breaks down the key value to build the hierarchy:

public void createNode(HashMap<String, String> map) {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("SQL Scripts");
        DefaultTreeModel treeModel = new DefaultTreeModel(root);
        tree.setModel(treeModel);
        Set<String> keys = map.keySet();
        Iterator<String> it = keys.iterator();
        while (it.hasNext()) {
            String key = it.next();
            String value = map.get(key);
            String[] path = key.split("/");
            DefaultMutableTreeNode parent = root;
            for (int i = 0; i < path.length; i++) {
                boolean found = false;
                int index = 0;
                Enumeration e = parent.children();
                while (e.hasMoreElements()) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
                    if (node.toString().equals(path[i])) {
                        found = true;
                        break;
                    }
                    index++;
                }
                if (!found) {
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode(path[i]);
                    treeModel.insertNodeInto(child, parent, index);
                    parent = child;
                } else {
                    parent = (DefaultMutableTreeNode) treeModel.getChild(parent, index);
                }
            }
            DefaultMutableTreeNode child = new DefaultMutableTreeNode(value);
            treeModel.insertNodeInto(child, parent, parent.getChildCount());
        }
    }

But for some reason that I can't indentify, it is not working. I still get the following result:

Result from createNode methode

Could anyone tell me what I did wrong on my code implementation?


Solution

  • The problem seems to be that you're trying to split a Windows file path using /, except, Windows file paths are separated by \, which of course is also an escape character of regular expressions 😓

    You could...

    Use key.replace(File.separatorChar, '/').split("/") to change the \ to / and the split on it

    Or...

    File file = new File(key);
    Path path = file.toPath();
    // Path path = Paths.get(key);
    for (int index = 0; index < path.getNameCount(); index++) {
        String subPath = path.getName(index));
        //...
    }
    

    Or...

    File file = new File(key);
    Path path = file.toPath();
    // Path path = Paths.get(key);
    Iterator<Path> it = path.iterator();
    while (it.hasNext()) {
        Path next = it.next();
        String subPath = path.getFileName();
        //...
    }