简体   繁体   中英

Dynamically add nodes in a JTree

I have data like this (has other data like percentage, but is not important now) in a List that can vary:

1        
1.1    
1.1.1  
1.1.2  
1.2        
2     
2.1
2.2 

How i easily work with the levels to build a proper JTree for any given levels? Can be done with recursion? What the best way?

Thank you so much.

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

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM