FYI: I checked other questions similar to mine but they didn't help, that's why I'm asking this question.
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:
Could anyone tell me what I did wrong on my code implementation?
CodePudding user response:
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