Link to home
Start Free TrialLog in
Avatar of sanjay_thakur
sanjay_thakur

asked on

Cloning nodes in JTree

Hi I have a basic tree.

Now I want to create Tree A and Tree B which will
have the nodes of basic tree and some additional
nodes.

I get the nodes of the basic tree by
 DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode)basicTree.                          getModel().getRoot();

Enumeration enum = rootNode.children();
childCount = rootNode.getChildCount();

The problem is once I add these nodes to Tree A
I cannot add these nodes to Tree B.

infact after adding the nodes to Tree A
if I do : childCount = rootNode.getChildCount();
I get childCount = 0;

I dont know how the basic tree gets affected
I think I have to do deep cloning and then
work on the  cloned node.

Any suggestions?

If I can see come code snippet of deep cloning
a node . it will be helpful

Structure of tree example:

fab ---- root node
 name ----node
  address --node
    city  --node

each of the children name, address, city
have multiple nodes.
I want to copy all the children of
the root node to multiple trees.
 











 

Avatar of Mick Barry
Mick Barry
Flag of Australia image

Well without seeing the code that's adding nodes it's a bit hard to help.
Sounds though, like what you need to do is create new instance of the node from tree A, to add to the tree B.
Here is deepClone sample:

MutableTreeNode deepClone(MutableTreeNode root){
    MutableTreeNode newRoot = (MutableTreeNode)root.clone();
    // Take care of user object cloning, if necessary.
    for(Enumeration childEnum = root.children(); childEnum.hasMoreElements();){
           newRoot.add(deepClone((MutableTreeNode)childEnum.nextElement()));
    }
}

Regards,
Igor Bazarny,
Brainbench MVP for Java 1
www.brainbench.com
ASKER CERTIFIED SOLUTION
Avatar of Igor Bazarny
Igor Bazarny
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
sanjay_thakur,

Most typical grades are A and B here. People typically explain source of dissatisfaction when assign "C" grade to answer.  If you have more questions anyone will try to make explanation more clear.

Thanks,
Igor Bazarny