Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store state/expanded nodes of a jtree for restoring state

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.

like image 922
Cratylus Avatar asked Oct 07 '10 05:10

Cratylus


2 Answers

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

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

like image 113
Steve Jackson Avatar answered Sep 25 '22 17:09

Steve Jackson


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);
    }
}
like image 44
Thomas Ziegenhein Avatar answered Sep 22 '22 17:09

Thomas Ziegenhein