Search code examples
javaswingclonejtreetreemodel

How to clone a java TreeModel?


I want to have 2 TreeModels: the root of the second TreeModel is a node of the first TreeModel (therefore, the second TreeModel is a subtree of the first TreeModel).

I think that I can easily do this by cloning the this TreeModel and changing the root. However, I don't know if there is an easy way of cloning TreeModel.


Solution

  • The default implementation of the interface TreeModel is DefaultTreeModel, which you can easily use here to instantiate a subtree model:

    TreeModel main = ...;
    // parent and index have to be defined
    TreeNode node = (TreeNode)main.getChild(parent, index);
    TreeModel sub = new DefaultTreeModel(node);