JTree node dynamic insertion

I have a list filled with duplicate entries. I use a hash to store every unique entry from this list. Each key then points to an object of type DefaultMutableTreeNode, which represents a JTree node. My goal is for this node to point to all entries from the list that have the same node name as the parent.

I added these parent nodes without problems, but when the child nodes are added (via insertNodeInto), only the parent nodes appear. Below is a snippet of code; I am very grateful for the advice / time.

// an unsorted list of items List<MyObject>list = hash.get(key); // clause to check for size if (list.size() > 0) { // iterate through each item in the list and fetch obj for (int i=0; i < list.size(); i++) { MyObject be = list.get(i); // if object is not in hash, add to hash and point obj to new node if (!hashParents.containsKey(be)) { DefaultMutableTreeNode parent = new DefaultMutableTreeNode(be.getSequence()); // add the key and jtree node to hash hashParents.put(be, parent); // insert node to tree, relead model ((DefaultMutableTreeNode)(root)).insert( new DefaultMutableTreeNode("parent node"), root.getChildCount()); ((DefaultTreeModel)(tree.getModel())).reload(); } // now that a parent-node exists, create a child DefaultMutableTreeNode child = new DefaultMutableTreeNode("child"); // insert the new child to the parent (from the hash) ((DefaultTreeModel)(tree.getModel())).insertNodeInto(child, hashParents.get(be), hashParents.get(be).getChildCount()); // render the tree visible ((DefaultTreeModel)(tree.getModel())).reload(); } } 
+4
source share
1 answer

You make a mistake here

 // insert node to tree, relead model ((DefaultMutableTreeNode)(root)).insert( new DefaultMutableTreeNode("parent node"), root.getChildCount()); 

You have already created the node parent above, but not using it. You insert another node into the tree, but the child nodes that you still insert into the parent . That is why they do not appear in the tree.

This piece of code looks like

 // insert node to tree, relead model ((DefaultMutableTreeNode)(root)).insert( parent, root.getChildCount()); 
0
source

Source: https://habr.com/ru/post/1393831/


All Articles