JTree add child to child to child etc

427 views Asked by At

i have a problem with my first jtree :-/

i have a list of nodes, like this:

List<DefaultMutableTreeNode> allNodes = new ArrayList<DefaultMutableTreeNode>();

and now i have to create a tree

if i loop over the nodes and create my tree, it looks like

-0
---1
-----2
-------3
-------4
-------5

...but i need this structure:

-0 (root)
---1 (child)
-----2 (child.child)
-------3 (child.child.child)
---------4 (...)
-----------5 (etc.)

what am i suppose to do at this point? any idea would be helpful. i tried many different ways, without success...

1

There are 1 answers

1
user2358582 On BEST ANSWER

You want to look at Recursion:

void addNode(Node parent, Node child, List<Node> nodes){
    parent.add(child);
    if(nodes.length > 1){
        nodes.remove(child);
        addNode(child, nodes[0],nodes);
    }
}