collapse Entire JTree - Java Swing

Java examples for Swing:JTree

Description

collapse Entire JTree

Demo Code

/*******************************************************************************
 * Copyright (c) JavaPEG developers//from   w w  w.ja v  a2s . c o  m
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
//package com.java2s;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.TreePath;
import java.util.*;

public class Main {
    @SuppressWarnings("unchecked")
    public static void collapseEntireTree(JTree tree,
            DefaultMutableTreeNode root, boolean collapseRoot) {

        Enumeration<DefaultMutableTreeNode> children = root.children();

        while (children.hasMoreElements()) {
            DefaultMutableTreeNode child = children.nextElement();

            if (child.children().hasMoreElements()) {
                collapseEntireTree(tree, child, collapseRoot);
            }
            tree.collapsePath(new TreePath(child.getPath()));
        }

        if (collapseRoot) {
            tree.collapsePath(new TreePath(root.getPath()));
        }
    }
}

Related Tutorials