swingjtreedefaultmutabletreenode

Add same DefaultMutableTreeNode to 2 different DefaultMutableTreeNode


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);

Solution

  • 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).