Java JTree Collapse collapseTree(JTree tree)

Here you can find the source of collapseTree(JTree tree)

Description

Collapse the tree

License

Open Source License

Parameter

Parameter Description
tree the tree to collapse

Declaration

public static void collapseTree(JTree tree) 

Method Source Code

//package com.java2s;
/*//from w w  w .j  av a  2  s .c o  m
The GUFF - The GNU Ultimate Framework Facility
Copyright (C) Simeosoft di Carlo Simeone
     
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
     
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.
     
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.util.Enumeration;

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

public class Main {
    /**
     * Collapse the tree
     * @param tree the tree to collapse
     */
    public static void collapseTree(JTree tree) {
        final DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        final DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        collapseSubTree(tree, root, model);
    }

    /**
     * Collapse the subtree starting at <code>startNode</code> node
     * @param tree the tree to collapse
     * @param startNode the starting point
     * @param model the tree model
     */
    private static void collapseSubTree(JTree tree, DefaultMutableTreeNode startNode, DefaultTreeModel model) {
        if (startNode.isLeaf()) {
            return;
        }
        for (Enumeration e = startNode.children(); e.hasMoreElements();) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
            collapseSubTree(tree, node, model);
        }
        TreePath tp = new TreePath(model.getPathToRoot(startNode));
        if (tree.isExpanded(tp)) {
            tree.collapsePath(tp);
            // senza questa istruzione, in alcuni casi non riusciamo a riportare
            // lo scrolling ad un nodo espanso
            tree.scrollPathToVisible(tp);
        }
    }
}

Related

  1. collapseAll(JTree tree)
  2. collapseAllNodes(JTree tree)
  3. collapseAllRows(JTree tree)
  4. collapseTree(JTree tree)
  5. fullSelectionCollapse(JTree tree)
  6. getTreeSelectedCollapsedIcon()
  7. setCollapsedIcon(JTree tree, Icon icon)