store state/expanded nodes of a jtree for restoring state
Asked Answered
J

3

9

I am working with JTree.

I would like to know what is best the way to know which nodes are expanded in a JTree so as to save its state (i.e. save all expanded paths). So that if I call model.reload() the Jtree would not stay collapsed, but I will be able to restore its original state to the user, i.e., all expanded nodes will be expanded.

Jesu answered 7/10, 2010 at 5:33 Comment(0)
P
7

Santhosh Kumar is one of my go-to guys for Swing Hacks.

Answer: http://www.javalobby.org/java/forums/t19857.html

Parks answered 7/10, 2010 at 12:13 Comment(2)
Mr. Kumar is not a hacker, he's a savior. If he were on SO, my rep would be stuck at -13.Paraldehyde
This site no longer exists and it is still marked as the top answer.Wisner
H
4

You need to store the TreePaths that were expanded and expand them again after reloading the TreeModel. All TreePaths that have a descendant are considered to be expanded. P.S. if you deleted paths, check after reloading if the path is still available.

public void reloadTree(JTree jYourTree) {
    List<TreePath> expanded = new ArrayList<>();
    for (int i = 0; i < jYourTree.getRowCount() - 1; i++) {
        TreePath currPath = getPathForRow(i);
        TreePath nextPath = getPathForRow(i + 1);
        if (currPath.isDescendant(nextPath)) {
            expanded.add(currPath);
        }
    }
    ((DefaultTreeModel)jYourTree.getModel()).reload();
    for (TreePath path : expanded) {
        jYourTree.expandPath(path);
    }
}
Hereditament answered 20/1, 2017 at 16:11 Comment(0)
C
1

I'm new to Java and this drove me nuts as well. But I figured it out...I think. Below works fine in my app, but I think it does have some risk of not working as expected in some unusual circumstances.

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

public class TreeState {

private final JTree tree;
private StringBuilder sb;

public TreeState(JTree tree){
    this.tree = tree;
}

public String getExpansionState(){

    sb = new StringBuilder();

    for(int i =0 ; i < tree.getRowCount(); i++){
        TreePath tp = tree.getPathForRow(i);
        if(tree.isExpanded(i)){
            sb.append(tp.toString());
            sb.append(",");
        }
    }

    return sb.toString();

}   

public void setExpansionState(String s){

    for(int i = 0 ; i<tree.getRowCount(); i++){
        TreePath tp = tree.getPathForRow(i);
        if(s.contains(tp.toString() )){
            tree.expandRow(i);
        }   
    }
}

}
Canonical answered 10/7, 2014 at 18:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.