Dynamically add nodes in an JTree

755 views Asked by At

i have got a problem to add nodes dynamically to my JTree.

I receive my JTree Informations via a RestAPI in json Format. The informations i need are the folderID and the folderName.

The folderID structure is like that:

1
1.1
6.8
7.1.1.1
1.2
etc.

So i need to define my nodelevel by the points of my folderIDs. I have searched for some code and found this one.

Dynamically add nodes in a JTree

But when i implement the code i get an error message: root cannot be resolved to a variable

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

        }

Could you help me find a solution for my problem ?

1

There are 1 answers

5
user7291698 On

You have to define the root first:

DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root")
JTree tree = new JTree(rootNode);

Then you can start to add nodes to the JTree by adding nodes to the root node.