Java JTree Expand expandAll(JTree tree, boolean expand)

Here you can find the source of expandAll(JTree tree, boolean expand)

Description

Expands or Collapses all tree nodes in the given JTree.

License

Open Source License

Parameter

Parameter Description
tree tree the operation is performed on.
expand true means expand the tree, false collapse it.

Declaration

public static void expandAll(JTree tree, boolean expand) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Enumeration;
import javax.swing.JTree;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class Main {
    /**/*w  w  w  .j a v  a  2s .co  m*/
     * Expands or Collapses all tree nodes in the given JTree. Internally
     * a recursive algorithm is used.
     * @param tree      tree the operation is performed on.
     * @param expand   true means expand the tree, false collapse it.
     */
    public static void expandAll(JTree tree, boolean expand) {
        expandAll(tree, expand, new TreePath(tree.getModel().getRoot()));
    }

    /**
     * Traverses all the children of the last component of the given tree path and calls
     * this method recursively on them and also expands or collapse the tree path.
     * @param tree      The working JTree
     * @param expand   true means expand the tree path, false collapse it.
     * @param parent
     */
    private static void expandAll(JTree tree, boolean expand, TreePath parent) {
        // Traverse children
        TreeNode node = (TreeNode) parent.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            for (Enumeration<?> e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                expandAll(tree, expand, path);
            }
        }

        // Expansion or collapse must be done bottom-up
        if (expand) {
            tree.expandPath(parent);
        } else {
            tree.collapsePath(parent);
        }
    }
}

Related

  1. expandAll(JTree rightTree)
  2. expandAll(JTree t)
  3. expandAll(JTree tree)
  4. expandAll(JTree tree)
  5. expandAll(JTree tree)
  6. expandAll(JTree tree, boolean expand)
  7. expandAllNode(JTree tree, TreePath parent)
  8. expandAllNodes(final JTree tree)
  9. expandAllNodes(JTree tree)