Add same DefaultMutableTreeNode to 2 different DefaultMutableTreeNode

165 views Asked by At

I have a DefaultMutableTreeNode("birds") which has n number of children. Now I want to add this node to 2 different parents DefaultMutableTreeNode("animals") & DefaultMutableTreeNodes("animals2").

But as the add or insert method of DefaultMutableTreeNode removes the child from it's parent first. The DefaultMutableTreeNode("birds") is getting added in only one of the parent node. Whichever is the called later.

Is there any way around this?

DefaultMutableTreeNode birds = new DefaultMutableTreeNode("birds");
DefaultMutableTreeNode animals = new DefaultMutableTreeNode("animals");
DefaultMutableTreeNode animals2 = new DefaultMutableTreeNode("animals2");
animals.add(birds);
animals2.add(birds);
2

There are 2 answers

0
mayur2j On BEST ANSWER

I finally ended up with below solution

JTree.DynamicUtilTreeNode.createChildren(DefaultMutableTreeNode parent, Object children) JTree myTree = new JTree(parent)

This takes a root node as input and children object can be either an array, vector or hashtable. I used hashtable initially to store all the tree's children(birds) and then added them to 2 different root nodes(animals & animals2).

0
Sergiy Medvynskyy On

If I correct understand your problem the best way is to create a method which provides "birds-hierarchy":

private DefaultMutableTreeNode createBirdsNode() {
    DefaultMutableTreeNode birds = new DefaultMutableTreeNode("birds");
    // add another nodes to birds node.
    return birds;
}

And later you can use this method to add the complete hierarchy.

animals.add(createBirdsNode());
animals2.add(createBirdsNode());