Skip to content
Advertisement

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

Advertisement

Answer

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());
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement