Java examples for Swing:JTree
If expand is true, expands all nodes in the JTree.
//package com.java2s; import java.util.Collection; import java.util.Enumeration; import javax.swing.JTree; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; public class Main { /**/*ww w. j a v a 2 s .c o m*/ * If expand is true, expands all nodes in the tree. * Otherwise, collapses all nodes in the tree. * * @param tree tree * @param expand true if expand all nodes */ public static void expandAll(JTree tree, boolean expand) { if (tree == null) { throw new NullPointerException("tree == null"); } TreeNode root = (TreeNode) tree.getModel().getRoot(); // Traverse tree from root expandAll(tree, new TreePath(root), expand); } /** * Expands or collapses a path and all it's sub paths. * * @param tree tree * @param parent parent path * @param expand true if expand, false if collapse * */ @SuppressWarnings("unchecked") public static void expandAll(JTree tree, TreePath parent, boolean expand) { if (tree == null) { throw new NullPointerException("tree == null"); } if (parent == null) { throw new NullPointerException("parent == null"); } // Traverse children TreeNode node = (TreeNode) parent.getLastPathComponent(); if (node.getChildCount() >= 0) { for (Enumeration<TreeNode> e = node.children(); e .hasMoreElements();) { TreeNode n = e.nextElement(); TreePath path = parent.pathByAddingChild(n); expandAll(tree, path, expand); } } // Expansion or collapse must be done bottom-up if (expand) { tree.expandPath(parent); } else { tree.collapsePath(parent); } } /** * Expands or collapses tree paths and all it's sub paths. * * @param tree tree * @param parentPaths parent paths * @param expand true if expand, false if collapse * */ public static void expandAll(JTree tree, Collection<? extends TreePath> parentPaths, boolean expand) { if (tree == null) { throw new NullPointerException("tree == null"); } if (parentPaths == null) { throw new NullPointerException("parentPaths == null"); } for (TreePath treePath : parentPaths) { expandAll(tree, treePath, expand); } } /** * ?ffnet den Tree auch, wenn das letzte Element eines Pfads ein Blatt ist. * * @param tree Tree * @param path Pfad */ public static void expandPath(JTree tree, TreePath path) { if (tree == null) { throw new NullPointerException("tree == null"); } if (path == null) { throw new NullPointerException("path == null"); } TreePath expandPath = path; if (tree.getModel().isLeaf(path.getLastPathComponent())) { expandPath = path.getParentPath(); } tree.expandPath(expandPath); } }