How do I display folders using a JTree in Java Swing?

Use a JTree to display folders in a hierarchy that users can expand and collapse. In this example, you will build a small project folder tree from sample names. The program does not read or modify any folders on your computer.

Source code

Save the following code as FolderTreeExample.java:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;

public class FolderTreeExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        var root = new DefaultMutableTreeNode("Project");
        var source = new DefaultMutableTreeNode("src");

        source.add(new DefaultMutableTreeNode("examples"));
        root.add(source);
        root.add(new DefaultMutableTreeNode("docs"));
        root.add(new DefaultMutableTreeNode("images"));

        JTree tree = new JTree(root);

        JFrame frame = new JFrame("Folder Tree");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(tree));
        frame.setSize(360, 220);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration of the Folder Tree window with Project and src expanded, showing examples under src

Explanation

Each DefaultMutableTreeNode represents one folder. Project is the root node, the top item in the tree. Calling root.add(source) makes src a child of Project.

The node you call add() on determines where the new item appears:

source.add(new DefaultMutableTreeNode("examples"));

This places examples under src. The docs and images nodes are added directly to root, so they appear at the same level as src.

new JTree(root) displays the hierarchy. Swing supplies the controls for expanding and collapsing branches, so this example does not need a click listener. The JScrollPane lets users scroll if the visible rows do not fit in the window.

Run the example

javac FolderTreeExample.java
java FolderTreeExample

Expand Project if needed, then expand src to reveal examples. Collapse src again: examples is hidden, while docs and images remain visible.

Wayan

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.