0

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);
Cœur
  • 37,241
  • 25
  • 195
  • 267
mayur2j
  • 141
  • 2
  • 13
  • 1
    No, it's not possible, because `DefaultMutableTreeNode` is used to represent trees, but in your case it's a graph. So you can only add a new node with the same text. – Sergiy Medvynskyy Jun 21 '17 at 13:27
  • What's the solution then? Can I duplicate the node and then add it?How can I duplicate? – mayur2j Jun 21 '17 at 13:56
  • Something like this: `animals2.add(new DefaultMutableTreeNode("birds"));` – Sergiy Medvynskyy Jun 21 '17 at 14:54
  • But that won't add the children of already existing birds node. I don't want to create new node with no children. I just want to add the node to another parent node. This seems so simple yet there is no explanation of it anywhere. – mayur2j Jun 21 '17 at 14:57

2 Answers2

1

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());
Sergiy Medvynskyy
  • 11,160
  • 1
  • 32
  • 48
0

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

mayur2j
  • 141
  • 2
  • 13