Reputation: 141
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);
Upvotes: 0
Views: 186
Reputation: 141
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).
Upvotes: 0
Reputation: 11327
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());
Upvotes: 1