Search code examples
javaswingjtree

Completely expand all node of a Jtree (including children)


I found some details on the internet for this problem but the solution does not seem to work.

I want to be able to expand all the nodes ( including the leaf nodes ) of a JTree. This is the code I have so far.

    tree = new JTree(treeModel);
    tree.setShowsRootHandles(true);
    tree.setEditable(true);
    tree.addTreeSelectionListener(treeSelectionListener);
    tree.addMouseListener(mouselistener);
    tree.setCellRenderer(new FileCellRenderer());

      for (int i = 0; i < tree.getRowCount(); i++) {
            
            tree.expandRow(i);
        }

This however does not expand all the leaf nodes. What I get is IMAGE A but what I want is IMAGE B:

IMAGE A IMAGE B


Solution

  • Use a recursive call, as in the following sample:

    private void expandAllNodes(JTree tree, int startingIndex, int rowCount){
        for(int i=startingIndex;i<rowCount;++i){
            tree.expandRow(i);
        }
    
        if(tree.getRowCount()!=rowCount){
            expandAllNodes(rowCount, tree.getRowCount());
        }
    }