I'm trying to find a solution the problem of collapse in JTree
after reload it.
The situation:
JTree
[-] Office A
|---[-] Office A.1
| |---[-] Office A.1.1
| |---[-] Office A.1.2
[-] Office B
|---[-] Office B.1
| |---[-] Office B.1.1
| | |---[-] Office B.1.1.1
Now I have to add the Office A.1.3
. To do this I get the Office A.1
and with the method add(DefaultMutableTreeNode aNode)
I add Office A.1.3
.
OfficeA1.add(OfficeA13);
After this I call the reload
method on the DefaultTreeModel
of the tree.
The problem is that after this call the tree collapse all:
[+] Office A
[+] Office B
And I have to manually expand the node Office A
to be sure that the node is added...
[-] Office A
|---[-] Office A.1
| |---[-] Office A.1.1
| |---[-] Office A.1.2
| |---[-] Office A.1.3
[+] Office B
My code...
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root not visibile");
DefaultMutableTreeNode usersRoot = new DefaultMutableTreeNode("Utenti");
DefaultMutableTreeNode groupsRoot = new DefaultMutableTreeNode("Gruppi");
DefaultMutableTreeNode officesRoot = new DefaultMutableTreeNode("Uffici")
root.add(usersRoot);
root.add(groupsRoot);
root.add(officesRoot);
JTree ccTree = new JTree(root);
and when I add node...
Office anOffice = //get the correct office object
DefaultTreeModel model = (DefaultTreeModel)competenzaTree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
DefaultMutableTreeNode n = (DefaultMutableTreeNode)root.getChildAt(0);
n.add(new DefaultMutableTreeNode(anOffice));
model.reload(n);
The problem is whit the officesRoot
node. The usersRoot
and groupsRoot
node are not hierarchical.
Is there a way to avoid this behavior ? Thanks.
Probably another way to ask can be which is the way to add/remove node from a tree without causing collapse of all tree ?
p.s. I also read this post but it did not help me.
Consider using
DefaultTreeModel#insertNodeInto(DefaultMutableNode, DefaultMutableNode, int)
which should inform theJTree
table that a new node has become available, cause theJTree
to be updated, but shouldn't effect the current expanded state of the treeThis example is based on the example found in How to use trees