Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 386
sdasdadas Avatar asked Mar 04 '13 20:03

sdasdadas


People also ask

How do you expand node JTree?

2) row numbers of tree nodes are not static. When we pass a row number to "expandRow(row)" method, suppose n, the tree will expand nth visible node from the root.

What is JTree swing?

JTree is a Swing component with which we can display hierarchical data. JTree is quite a complex component. A JTree has a 'root node' which is the top-most parent for all nodes in the tree. A node is an item in a tree. A node can have many children nodes.


1 Answers

The following worked for me (called after setting the new model):

for (int i = 0; i < tree.getRowCount(); i++) {     tree.expandRow(i); } 
like image 195
sdasdadas Avatar answered Oct 04 '22 11:10

sdasdadas