[Solved] Dynamically add nodes in a JTree


Yes, it can easily be done using recursion. The idea is to check if there is already a node in the tree under which the new node can be fallen. For example, if the new node is “1.1.2”, then we have to check if the node “1.1” exists in the tree. I wrote a very simple code and it is working, I am going yo cope here. If you don’t understand something then just let me know, I will explain you. The function to check if the tree has the node of a particular string is given below.

public DefaultMutableTreeNode findparentnode(String s,DefaultMutableTreeNode root){
    DefaultMutableTreeNode parent=null;
    for (int i=0;i<root.getChildCount();i++) {
        if(s.equalsIgnoreCase(((DefaultMutableTreeNode)root.getChildAt(i)).toString())){
             parent = (DefaultMutableTreeNode)root.getChildAt(i);
            break;
        }
        else
            parent=findparentnode(s, (DefaultMutableTreeNode)root.getChildAt(i));
    }
    return parent;
}

Now, we will check every string in the list. We will skip the last part of the string, and will pass the remaining value to the function. To check the string, the code is given below

for(String s:list){
            String[] substr=s.split("\\.");
            String parent=substr[0];
            for(int i=1;i<substr.length-1;i++){
                parent=parent+ "." + substr[i];
            }
            DefaultMutableTreeNode node=null;
            node=findparentnode(parent,root);


            if(node==null)
                root.add(new DefaultMutableTreeNode(s));
            else
                node.add(new DefaultMutableTreeNode(s));

        }

solved Dynamically add nodes in a JTree