Search code examples
javaswingtreejtree

How do I auto-expand a JTree when setting a new TreeModel?


I have a custom JTree and a custom JModel; I would for the JTree to "auto-expand" when I give it a new model. At the moment, it simply collapse all the nodes to the root.

Here is an example:

private class CustomTree extends JTree {

    @Override
    public boolean isExpanded(TreePath path) {
        return ((Person) path.getLastPathComponent).hasChildren();

}

private class CustomTreeModel extends TreeModel {

    // ... omitting various implementation details

    @Override
    public boolean isLeaf(Object object) {
        return !((Person) object).hasChildren();
    }

}

Model model = new Model();
Person bob = new Person();
Person alice = new Person();
bob.addChild(alice);
model.setRoot(bob);
JTree tree = new CustomTree(new CustomTreeModel(model));

At this point, the tree correctly displays:

- BOB
  - ALICE

where Alice is a child of Bob (both in the data and in the visual tree)

However, if I call:

tree.setModel(new CustomTreeModel(model));

everything is collapsed:

+ BOB

Is there a way to "auto-expand" everything in the tree when setting a new model?


Solution

  • I had a similar problem.

    Your solution (as posted https://stackoverflow.com/a/15211697/837530) seemed to work for me only for the top level tree nodes.

    But I needed to expand all the a descendants node. So I solved it with the following recursive method:

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

    which is invoked with

    expandAllNodes(tree, 0, tree.getRowCount());
    

    where, tree is a JTree.

    Unless someone has a better solution.