title: How to collapse JTree nodes?
body: <p>I want to implement a requirement where in I have to collapse all child nodes of <code>JTree</code>.</p>
  
  <p>I am using <strong>jdk1.6.</strong></p>
  
  <p>Note: Only the child nodes of root element are to be collapsed on button click.</p>
  
  <p>Here is my code:</p>
  
  <pre class="lang-java prettyprint-override"><code>private static void collapseAll(JTree tree, TreePath parent) { 
         TreeNode node = (TreeNode)parent.getLastPathComponent(); 
         if (!node.isLeaf() &amp;&amp; node.getChildCount()&gt;=0) { 
            Enumeration e = node.children(); 
            while (e.hasMoreElements()) { 
               TreeNode n =  (TreeNode)e.nextElement(); 
               TreePath path = parent.pathByAddingChild(n); 
               collapseAll(tree, path); 
            }
         } 
        tree.collapsePath(parent); 
  }
  </code></pre>