Page 5
Retrieve all frames from an image (e.g. animated GIF)
Page 6
Index
See this article in english  Ver este artículo en español 
 

Collapse or Expand completely a JTree

Alexander Hristov

The following two methods allow you to fully expand or collapse a JTree. Unfortunately, the only way of doing this is recursively walking the tree, expanding all nodes from the bottom up.

TreeState.java
 
import javax.swing.JTree;
import javax.swing.tree.TreePath;

public class TreeState {
  public static void setTreeState(JTree tree, boolean expanded) {
    Object root = tree.getModel().getRoot();
    setTreeState(tree, new TreePath(root),expanded);
  }
  
  public static void setTreeState(JTree tree, TreePath path, boolean expanded) {
    Object lastNode = path.getLastPathComponent();
    for (int i = 0; i < tree.getModel().getChildCount(lastNode); i++) {
      Object child = tree.getModel().getChild(lastNode,i);
      TreePath pathToChild = path.pathByAddingChild(child);
      setTreeState(tree,pathToChild,expanded);
    }
    if (expanded) 
      tree.expandPath(path);
    else
      tree.collapsePath(path);
      
    
  }
}

 


Source code



 

Comments

 

Add a Comment

Name (optional)
EMail (optional, will not be displayed)

Text