Close

Java Swing - How to Collapse or Expand All Nodes of JTree?

[Last Updated: Jul 4, 2018]

This example shows how to expand or collapse all nodes of a JTree programmatically.

Example

Expand/Collapse JTree nodes

package com.logicbig.example;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.util.ArrayList;
import java.util.Collections;

public class JTreeUtil {
    public static void setTreeExpandedState(JTree tree, boolean expanded) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getModel().getRoot();
        setNodeExpandedState(tree, node, expanded);
    }

    public static void setNodeExpandedState(JTree tree, DefaultMutableTreeNode node, boolean expanded) {
        ArrayList<DefaultMutableTreeNode> list = Collections.list(node.children());
        for (DefaultMutableTreeNode treeNode : list) {
            setNodeExpandedState(tree, treeNode, expanded);
        }
        if (!expanded && node.isRoot()) {
            return;
        }
        TreePath path = new TreePath(node.getPath());
        if (expanded) {
            tree.expandPath(path);
        } else {
            tree.collapsePath(path);
        }
    }
}

Creating JTree

public class TreeExampleMain {
    public static void main(String[] args) {
        Hashtable<?, ?> projectHierarchyMap =
                TradingProjectDataService.instance.getProjectHierarchy();
        JTree tree = new JTree(projectHierarchyMap);
        JFrame frame = createFrame();
        frame.add(new JScrollPane(tree));
        frame.add(createTopPanel(tree), BorderLayout.NORTH);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static JComponent createTopPanel(JTree tree) {
        JPanel panel = new JPanel();
        JButton expandBtn = new JButton("Expand All");
        expandBtn.addActionListener(ae-> {
            JTreeUtil.setTreeExpandedState(tree, true);
        });
        panel.add(expandBtn);
        JButton collapseBtn = new JButton("Collapse All");
        collapseBtn.addActionListener(ae-> {JTreeUtil.setTreeExpandedState(tree, false);});
        panel.add(collapseBtn);
        return panel;
    }

    private static JFrame createFrame() {
        JFrame frame = new JFrame("JTree Expand/Collapse example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(new Dimension(500, 400));
        return frame;
    }
}

Output

On clicking 'Expand All' button:

Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.3.9

JTree Collapse/Expand All Nodes Example Select All Download
  • jtree-expand-programmatically
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • JTreeUtil.java
                • util

    See Also