First of all, you must have this in mind -- JTree takes care of how the tree is presented whereas DefaultMutableTreeNode does all the structual data manipulation such as adding or deleting a TreeNode. My point here is this -- there are JTree and DefaultMutableTreeNode and JTree is not equipped with method that can access to a TreeNode object. JTree must access to TreeNode via TreePath. The following code shows the process, to collapse a tree node.
TreeNode list[]=node.getPath();
TreePath path=new TreePath(list);
tree.collapsePath(path);
The TreePath can point to a TreeNode, and PathComponent and TreeNode is used in method names interchangeably, so this can be confusing. This line shows how to get the selected TreeNode of a JTree.
DefaultMutableTreeNode selectedNode=
(DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
Lastly, this will collapse all the TreeNode in a JTree.
void collapseNode(DefaultMutableTreeNode n)
{
for (Enumeration e=n.postorderEnumeration(); e.hasMoreElements() ; )
{
DefaultMutableTreeNode node=(DefaultMutableTreeNode)e.nextElement();
TreeNode list[]=node.getPath();
TreePath path=new TreePath(list);
if(!node.isRoot())
{
tree.collapsePath(path);
}
}
}