Swing Trees: JTree, Tree Models, Nodes and Paths
Showing hierarchical data with JTree: DefaultMutableTreeNode and DefaultTreeModel, root handles and forests, tree paths and rows, editing through the model, node enumerations, selection events, cell renderers, and writing a lazy custom TreeModel.
kvi5hnuCode Sprout team member12 min readOn this page
File systems, organization charts, package structures, XML documents, a music library sorted by genre: hierarchies are everywhere, and JTree displays them. It draws the nodes with indentation and icons, lets the user expand and collapse subtrees, select nodes and optionally edit them. As with tables, the component itself only displays; the data comes from a tree model.
First, some terms. A tree consists of nodes. One node is the root; every other node has exactly one parent. A node without children is a leaf. A collection of several trees, each with its own root, is a forest.
A simple tree
Swing's standard node class is DefaultMutableTreeNode. Each node holds a user object, which the tree displays with toString(), and links to its parent and children:
var root = new DefaultMutableTreeNode("Library");
var rock = new DefaultMutableTreeNode("Rock");
root.add(rock);
rock.add(new DefaultMutableTreeNode("Abbey Road"));
...
var model = new DefaultTreeModel(root);
var tree = new JTree(model); // or new JTree(root), which creates the model
frame.add(new JScrollPane(tree));
User objects can be any objects: strings for a demo, Path objects for a file browser, domain records in an application. setUserObject changes it later.
DefaultMutableTreeNode implements MutableTreeNode, which extends TreeNode; DefaultTreeModel works with any TreeNodes. (There are also JTree constructors that take an array, a Vector or a Hashtable of objects; they build a forest of single nodes and are rarely useful.)
Initially, the tree shows the root and its children. Clicking a node's handle expands or collapses it. The appearance of handles and lines depends on the look and feel; in Metal, the client property "JTree.lineStyle" selects "Angled" lines (the default), "Horizontal" separators between the root's children, or "None".
Root handles and forests
The root normally has no handle. tree.setShowsRootHandles(true) adds one, so the user can collapse the whole tree. To present a forest, join the trees under one root and hide it with tree.setRootVisible(false): the root's children then appear as top-level nodes. Turn on root handles too, or the top-level nodes cannot be collapsed. The demo shows such a forest.
Leaves and folders
The tree draws each node with an icon: a leaf icon, or a folder icon (open or closed). It asks the model whether a node is a leaf, and by default a DefaultMutableTreeNode is a leaf when it has no children. That is not always right: an empty genre or an empty directory is not conceptually a leaf. Mark the nodes that can never have children with node.setAllowsChildren(false) and tell the model to use this property instead:
model.setAsksAllowsChildren(true);
var tree = new JTree(root, true); // the same, for a model created by the tree
In the demo, "Jazz" has no children; isLeaf() says it is a leaf, but the model, asking about allowed children, shows it as a folder.
Tree paths and rows
JTree does not know about TreeNodes at all. The model interface describes the tree with plain Objects (the root, the children of a node), so the nodes of a custom model need not have getParent methods. For that reason, the tree identifies a node by its tree path: the sequence of objects from the root down to the node.

A TreePath holds that sequence. Usually you need only its end, getLastPathComponent(). Other methods are getPathCount(), getParentPath(), getPath() (the array) and pathByAddingChild(child). To find the selected node:
TreePath selected = tree.getSelectionPath(); // null if nothing is selected
var node = (DefaultMutableTreeNode) selected.getLastPathComponent();
var same = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); // shortcut
The shortcut is not called "getSelectedNode" for the same reason: the tree does not know that its objects are nodes. To build a path for a node, DefaultTreeModel.getPathToRoot(node) (or node.getPath()) returns the array of nodes from the root, which the TreePath constructor accepts.
Many JTree methods also have versions that take a row, the position of a node among the currently visible nodes (getPathForRow, getRowForPath, expandRow). Rows change whenever anything above them is expanded or collapsed, and hidden nodes have no row at all: in the demo, Bolero's row is -1 until makeVisible expands its parent, and then 7. Prefer paths in your code.
Editing trees
Changing a node's children directly, as in selectedNode.add(newNode), changes the data but not the display: no event reaches the tree, which keeps showing the old structure. The demo adds an album this way, and the tree's row count stays the same. Make changes through DefaultTreeModel, which updates the nodes and notifies its listeners:
model.insertNodeInto(newNode, parent, index); // add a child
model.removeNodeFromParent(node); // remove a node and its subtree
model.nodeChanged(node); // after changing the user object
model.nodesWereInserted(parent, childIndexes); // after you changed nodes yourself
model.reload() rebuilds everything, but it also collapses the tree, which annoys users; use it only after wholesale changes.
A node added to a collapsed parent is invisible, so the user sees no effect. Expand its parents with tree.makeVisible(path), or better, tree.scrollPathToVisible(path), which also scrolls the enclosing scroll pane to show it:
model.insertNodeInto(newNode, selected, selected.getChildCount());
tree.scrollPathToVisible(new TreePath(model.getPathToRoot(newNode)));
To let the user rename nodes, call tree.setEditable(true): a triple click, a second click on an already selected node, or F2 opens a text field over the node (a double click is reserved for expanding and collapsing), and Enter commits. The tree then calls the model's valueForPathChanged, which in DefaultTreeModel sets the user object to the edited string; override it if your user objects are not strings. Other editors can be installed with setCellEditor, as with tables.
Enumerating nodes
DefaultMutableTreeNode can visit all nodes of a subtree in several orders:
breadthFirstEnumeration(): level by level, the root first, then its children, then the grandchildren;preorderEnumeration(): depth-first, each node before its children;postorderEnumeration(), or its synonymdepthFirstEnumeration(): depth-first, each node after its children.
pathFromAncestorEnumeration(ancestor) lists the nodes from an ancestor down to the node. Searching for a user object is a typical use:
for (var e = root.breadthFirstEnumeration(); e.hasMoreElements(); ) {
var node = (DefaultMutableTreeNode) e.nextElement();
if (node.getUserObject().equals(target)) return node;
}
Collections.list(enumeration) turns an enumeration into a list for streams. Other node queries are getLevel() (distance from the root), getDepth() (height of the subtree), getLeafCount(), getChildCount(), getIndex(child) and isNodeAncestor.
Selection events
To react when the user selects nodes, add a TreeSelectionListener:
tree.addTreeSelectionListener(event -> {
TreePath path = tree.getSelectionPath();
if (path != null) showDetails(path.getLastPathComponent());
});
The selection mode lives in the tree's TreeSelectionModel: SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION (the default, with Ctrl and Shift clicks in most look and feels):
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
Note that the event's getPaths() describes the change (added and removed paths, distinguished with isAddedPath), not the current selection. Ask the tree with getSelectionPaths() or getSelectionPath() for that.
Expanding and collapsing also produce events: a TreeExpansionListener hears about them afterwards, and a TreeWillExpandListener beforehand, so it can load children on demand or throw an ExpandVetoException to prevent the change.
Rendering nodes
A DefaultTreeCellRenderer, a JLabel subclass, draws each node as an icon and text. (The expansion handles are drawn by the look and feel, not the renderer.) There are three levels of customization:
- Change the icons for the whole tree:
setLeafIcon,setOpenIcon,setClosedIconon a renderer, thentree.setCellRenderer(renderer). - Subclass
DefaultTreeCellRendererand adjust the label per node. - Implement
TreeCellRendereryourself for completely custom drawing.
For the second option, override getTreeCellRendererComponent, call the superclass method to set up the label, and then change it:
class GenreRenderer extends DefaultTreeCellRenderer {
private Font plain;
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
if (plain == null) plain = getFont();
var node = (DefaultMutableTreeNode) value; // the node, not the user object
setFont(node.getLevel() == 1 ? plain.deriveFont(Font.BOLD) : plain);
return this;
}
}
Two traps are visible here. The value parameter is the node object from the model, not its user object; with DefaultMutableTreeNodes, call getUserObject() yourself. And as with table renderers, one label is reused for every node: if you make one node bold, you must make the next one plain again. Avoid setting fonts and colors for the whole tree; that is the look and feel's job.
Custom tree models
DefaultTreeModel requires building a tree of node objects. If your data is already hierarchical (a file system, objects linked by references, a parsed document), copying it into nodes wastes memory and must be kept in sync. Implement TreeModel directly instead. The tree calls it only as the user expands nodes:
| Method | Purpose |
|---|---|
Object getRoot() | the root object |
int getChildCount(Object parent) | number of children |
Object getChild(Object parent, int index) | one child |
int getIndexOfChild(Object parent, Object child) | the reverse of getChild |
boolean isLeaf(Object node) | draw as a leaf (no handle)? |
void valueForPathChanged(TreePath path, Object newValue) | the user edited a node |
addTreeModelListener, removeTreeModelListener | register the tree |
The first three describe the structure; for a read-only tree, the others are routine. Children must be consistent: return equal objects for the same child each time (records or cached objects work well), because the tree compares them with equals to keep track of expanded paths.
When the data change, the model must fire TreeModelEvents to its listeners through treeNodesChanged, treeNodesInserted, treeNodesRemoved or treeStructureChanged. The event names the parent's path and the indexes of the affected children; for wholesale changes, treeStructureChanged with the path of the changed subtree is simplest. javax.swing.event.EventListenerList handles the listener bookkeeping.
Because children are produced on demand, a model can even describe an infinite tree. The demo's model generates the Stern-Brocot tree, in which every positive fraction appears exactly once: each fraction's two children are formed from it and its nearest neighbors above. Only the expanded part ever exists. The listing below uses the same idea for the file system, reading a directory only when the user opens it.
A file browser
This program shows a directory tree with a custom, lazily loading TreeModel over Path objects: directories are listed only when expanded, cached, and refreshed on request by firing treeStructureChanged. A renderer shows file names with the look and feel's file and folder icons, and a selection listener displays file attributes.
import java.awt.*;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.List;
import java.util.stream.Stream;
import javax.swing.*;
import javax.swing.event.EventListenerList;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.*;
public final class FileTreeFrame extends JFrame {
private static final long serialVersionUID = 1L;
/** A tree model over the file system: children are read only when a directory is expanded. */
static final class FileTreeModel implements TreeModel {
private final Path root;
private final Map<Path, List<Path>> cache = new HashMap<>();
private final EventListenerList listeners = new EventListenerList();
FileTreeModel(Path root) { this.root = root; }
private List<Path> children(Object parent) {
return cache.computeIfAbsent((Path) parent, dir -> {
if (!Files.isDirectory(dir)) return List.of();
try (Stream<Path> entries = Files.list(dir)) {
return entries.filter(p -> !p.getFileName().toString().startsWith("."))
.sorted(Comparator.comparing((Path p) -> !Files.isDirectory(p)) // directories first
.thenComparing(p -> p.getFileName().toString().toLowerCase()))
.toList();
} catch (IOException | UncheckedIOException e) {
return List.of(); // unreadable directory: show it empty
}
});
}
public Object getRoot() { return root; }
public int getChildCount(Object parent) { return children(parent).size(); }
public Object getChild(Object parent, int index) { return children(parent).get(index); }
public int getIndexOfChild(Object parent, Object child) { return children(parent).indexOf(child); }
public boolean isLeaf(Object node) { return !Files.isDirectory((Path) node); }
public void valueForPathChanged(TreePath path, Object newValue) { }
/** Forget a directory's cached contents and tell the tree that its subtree changed. */
void refresh(TreePath path) {
cache.remove((Path) path.getLastPathComponent());
var event = new TreeModelEvent(this, path);
for (TreeModelListener l : listeners.getListeners(TreeModelListener.class))
l.treeStructureChanged(event);
}
public void addTreeModelListener(TreeModelListener l) { listeners.add(TreeModelListener.class, l); }
public void removeTreeModelListener(TreeModelListener l) { listeners.remove(TreeModelListener.class, l); }
}
/** Shows file names instead of full paths, with the look and feel's file and folder icons. */
static final class FileRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = 1L;
@Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
var path = (Path) value;
Path name = path.getFileName();
setText(name == null ? path.toString() : name.toString()); // the root has no file name
setIcon(UIManager.getIcon(leaf ? "FileView.fileIcon" : "FileView.directoryIcon"));
return this;
}
}
private final transient FileTreeModel model;
private final JTree tree;
private final JTextArea info = new JTextArea(10, 30);
public FileTreeFrame(Path start) {
super("Files");
model = new FileTreeModel(start);
tree = new JTree(model);
tree.setCellRenderer(new FileRenderer());
tree.setShowsRootHandles(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(_ -> showInfo());
info.setEditable(false);
var split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
new JScrollPane(tree), new JScrollPane(info));
split.setResizeWeight(0.5);
add(split, BorderLayout.CENTER);
var refresh = new JButton("Refresh");
refresh.addActionListener(_ -> {
TreePath selected = tree.getSelectionPath();
if (selected != null && !model.isLeaf(selected.getLastPathComponent())) model.refresh(selected);
});
var south = new JPanel(new FlowLayout(FlowLayout.TRAILING));
south.add(refresh);
add(south, BorderLayout.SOUTH);
setSize(700, 450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
}
private void showInfo() {
TreePath selected = tree.getSelectionPath();
if (selected == null) {
info.setText("");
return;
}
var path = (Path) selected.getLastPathComponent();
try {
var attrs = Files.readAttributes(path, BasicFileAttributes.class);
info.setText("""
Path: %s
Type: %s
Size: %,d bytes
Modified: %s
Depth: %d (tree path length)
""".formatted(path, attrs.isDirectory() ? "directory" : "file", attrs.size(),
attrs.lastModifiedTime(), selected.getPathCount()));
} catch (IOException e) {
info.setText("Cannot read " + path + ": " + e.getMessage());
}
}
public static void main(String[] args) {
Path start = Path.of(args.length > 0 ? args[0] : System.getProperty("user.home"));
EventQueue.invokeLater(() -> new FileTreeFrame(start).setVisible(true));
}
}
The program
The demo builds a tree and a JTree without showing it. Row-based queries work as soon as the tree has a model, which lets the demo print what the user would see, with v for expanded and > for collapsed nodes.
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public class Solution {
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
EventQueue.invokeAndWait(Solution::run);
}
static DefaultMutableTreeNode node(String name, DefaultMutableTreeNode... children) {
var n = new DefaultMutableTreeNode(name);
for (var c : children) n.add(c);
return n;
}
/** The rows a JTree would show right now, with expansion handles. */
static void showRows(String title, JTree tree) {
System.out.println(title + " (" + tree.getRowCount() + " rows)");
for (int row = 0; row < tree.getRowCount(); row++) {
TreePath path = tree.getPathForRow(row);
Object node = path.getLastPathComponent();
boolean leaf = tree.getModel().isLeaf(node);
String handle = leaf ? " " : tree.isExpanded(path) ? "v " : "> ";
int depth = path.getPathCount() - (tree.isRootVisible() ? 1 : 2);
System.out.println(" " + " ".repeat(depth) + handle + node);
}
}
static void run() {
var root = node("Library",
node("Rock", node("Abbey Road"), node("Rumours")),
node("Classical", node("Goldberg Variations"), node("The Four Seasons"), node("Bolero")),
node("Jazz")); // a genre without albums (yet)
var model = new DefaultTreeModel(root);
var tree = new JTree(model);
System.out.println("== A JTree over DefaultMutableTreeNodes ==");
showRows("initially", tree);
tree.expandRow(1);
showRows("after expanding Rock", tree);
model.setAsksAllowsChildren(true);
var jazz = (DefaultMutableTreeNode) root.getChildAt(2);
for (var e = root.depthFirstEnumeration(); e.hasMoreElements(); ) {
var n = (DefaultMutableTreeNode) e.nextElement();
n.setAllowsChildren(n.getLevel() < 2); // genres may have children, albums not
}
System.out.println("Jazz is a leaf? isLeaf()=" + jazz.isLeaf()
+ ", model.isLeaf()=" + model.isLeaf(jazz) + " (asks allowsChildren)");
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
showRows("root hidden: a forest", tree);
tree.setRootVisible(true);
System.out.println();
System.out.println("== Tree paths ==");
var bolero = (DefaultMutableTreeNode) root.getChildAt(1).getChildAt(2);
var path = new TreePath(model.getPathToRoot(bolero));
System.out.println("path " + path + ", length " + path.getPathCount());
System.out.println("last component " + path.getLastPathComponent() + ", parent path " + path.getParentPath());
System.out.println("visible before: row " + tree.getRowForPath(path));
tree.makeVisible(path); // expands Classical
System.out.println("visible after makeVisible: row " + tree.getRowForPath(path));
System.out.println("node at row 3: " + tree.getPathForRow(3).getLastPathComponent());
System.out.println();
System.out.println("== Changing the tree through the model ==");
model.addTreeModelListener(new TreeModelListener() {
public void treeNodesChanged(TreeModelEvent e) { log("changed", e); }
public void treeNodesInserted(TreeModelEvent e) { log("inserted", e); }
public void treeNodesRemoved(TreeModelEvent e) { log("removed", e); }
public void treeStructureChanged(TreeModelEvent e) { log("structure changed", e); }
void log(String what, TreeModelEvent e) {
System.out.println(" event: " + what + " under " + e.getTreePath().getLastPathComponent()
+ " at " + java.util.Arrays.toString(e.getChildIndices()));
}
});
var kindOfBlue = new DefaultMutableTreeNode("Kind of Blue", false);
model.insertNodeInto(kindOfBlue, jazz, jazz.getChildCount());
tree.scrollPathToVisible(new TreePath(kindOfBlue.getPath()));
model.removeNodeFromParent((DefaultMutableTreeNode) root.getChildAt(0).getChildAt(1));
bolero.setUserObject("Bolero (Ravel)");
model.nodeChanged(bolero);
var silent = new DefaultMutableTreeNode("Blue Train", false);
jazz.add(silent); // no event: the tree does not know
System.out.println("after jazz.add: jazz has " + jazz.getChildCount() + " children, tree shows "
+ tree.getRowCount() + " rows");
model.nodesWereInserted(jazz, new int[] {1}); // tell it after the fact
System.out.println("after nodesWereInserted: " + tree.getRowCount() + " rows");
showRows("current tree", tree);
System.out.println();
System.out.println("== Enumerating nodes ==");
System.out.println("breadth-first: " + names(root.breadthFirstEnumeration()));
System.out.println("pre-order: " + names(root.preorderEnumeration()));
System.out.println("post-order: " + names(root.postorderEnumeration()));
System.out.println("depth " + root.getDepth() + ", leaves " + root.getLeafCount()
+ ", Kind of Blue level " + kindOfBlue.getLevel());
System.out.println();
System.out.println("== Selection ==");
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
tree.addTreeSelectionListener(e -> {
List<String> changes = new ArrayList<>();
for (TreePath p : e.getPaths())
changes.add((e.isAddedPath(p) ? "+" : "-") + p.getLastPathComponent());
System.out.println(" selection event " + changes);
});
tree.setSelectionPath(path);
tree.addSelectionPath(new TreePath(kindOfBlue.getPath()));
tree.removeSelectionPath(path);
System.out.println("current selection: " + tree.getLastSelectedPathComponent()
+ ", " + tree.getSelectionCount() + " path(s)");
System.out.println();
System.out.println("== Renderer ==");
var renderer = new DefaultTreeCellRenderer() {
private static final long serialVersionUID = 1L;
private Font plain;
@Override public Component getTreeCellRendererComponent(JTree t, Object value, boolean sel,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(t, value, sel, expanded, leaf, row, hasFocus);
if (plain == null) plain = getFont();
var n = (DefaultMutableTreeNode) value; // the node, not the user object
boolean genre = n.getLevel() == 1;
if (plain != null) setFont(genre ? plain.deriveFont(Font.BOLD) : plain); // reset every time
return this;
}
};
tree.setCellRenderer(renderer);
for (int row : new int[] {1, 2}) {
Object value = tree.getPathForRow(row).getLastPathComponent();
var label = (JLabel) renderer.getTreeCellRendererComponent(tree, value, false,
tree.isExpanded(row), model.isLeaf(value), row, false);
System.out.println(" row " + row + ": \"" + label.getText() + "\" bold=" + label.getFont().isBold()
+ ", icon " + (label.getIcon() == renderer.getLeafIcon() ? "leaf"
: label.getIcon() == renderer.getOpenIcon() ? "open" : "closed"));
}
System.out.println();
System.out.println("== A custom TreeModel: the infinite Stern-Brocot tree ==");
var fractions = new JTree(new SternBrocotModel());
fractions.setShowsRootHandles(true);
fractions.expandRow(0);
fractions.expandRow(1);
fractions.expandRow(4);
showRows("expanded on demand", fractions);
}
static String names(Enumeration<TreeNode> e) {
List<String> list = new ArrayList<>();
for (TreeNode n : Collections.list(e)) {
list.add(n.toString().split(" ")[0]); // first word of each name
}
return String.join(" ", list);
}
/** A fraction p/q; its children are the mediants with its neighbors. */
record Fraction(int p, int q, int lp, int lq, int rp, int rq) {
@Override public String toString() { return p + "/" + q; }
Fraction left() { return new Fraction(p + lp, q + lq, lp, lq, p, q); }
Fraction right() { return new Fraction(p + rp, q + rq, p, q, rp, rq); }
}
static class SternBrocotModel implements TreeModel {
private final Fraction root = new Fraction(1, 1, 0, 1, 1, 0);
private final EventListenerList listeners = new EventListenerList();
public Object getRoot() { return root; }
public int getChildCount(Object parent) { return 2; }
public Object getChild(Object parent, int index) {
var f = (Fraction) parent;
return index == 0 ? f.left() : f.right();
}
public int getIndexOfChild(Object parent, Object child) {
var f = (Fraction) parent;
return f.left().equals(child) ? 0 : f.right().equals(child) ? 1 : -1;
}
public boolean isLeaf(Object node) { return false; }
public void valueForPathChanged(TreePath path, Object newValue) { } // not editable
public void addTreeModelListener(TreeModelListener l) { listeners.add(TreeModelListener.class, l); }
public void removeTreeModelListener(TreeModelListener l) { listeners.remove(TreeModelListener.class, l); }
}
}
== A JTree over DefaultMutableTreeNodes ==
initially (4 rows)
v Library
> Rock
> Classical
Jazz
after expanding Rock (6 rows)
v Library
v Rock
Abbey Road
Rumours
> Classical
Jazz
Jazz is a leaf? isLeaf()=true, model.isLeaf()=false (asks allowsChildren)
root hidden: a forest (5 rows)
v Rock
Abbey Road
Rumours
> Classical
> Jazz
== Tree paths ==
path [Library, Classical, Bolero], length 3
last component Bolero, parent path [Library, Classical]
visible before: row -1
visible after makeVisible: row 7
node at row 3: Rumours
== Changing the tree through the model ==
event: inserted under Jazz at [0]
event: removed under Rock at [1]
event: changed under Classical at [2]
after jazz.add: jazz has 2 children, tree shows 9 rows
event: inserted under Jazz at [1]
after nodesWereInserted: 10 rows
current tree (10 rows)
v Library
v Rock
Abbey Road
v Classical
Goldberg Variations
The Four Seasons
Bolero (Ravel)
v Jazz
Kind of Blue
Blue Train
== Enumerating nodes ==
breadth-first: Library Rock Classical Jazz Abbey Goldberg The Bolero Kind Blue
pre-order: Library Rock Abbey Classical Goldberg The Bolero Jazz Kind Blue
post-order: Abbey Rock Goldberg The Bolero Classical Kind Blue Jazz Library
depth 2, leaves 6, Kind of Blue level 2
== Selection ==
selection event [+Bolero (Ravel)]
selection event [+Kind of Blue]
selection event [-Bolero (Ravel)]
current selection: Kind of Blue, 1 path(s)
== Renderer ==
row 1: "Rock" bold=true, icon open
row 2: "Abbey Road" bold=false, icon leaf
== A custom TreeModel: the infinite Stern-Brocot tree ==
expanded on demand (7 rows)
v 1/1
v 1/2
> 1/3
> 2/3
v 2/1
> 3/2
> 3/1
Points to notice:
- Hiding the root produced a forest; with
asksAllowsChildren, the empty Jazz genre got an expansion handle. insertNodeInto,removeNodeFromParentandnodeChangedeach fired an event naming the parent and the child index. The directjazz.addfired nothing, and the tree caught up only afternodesWereInserted.- Breadth-first visits genres before albums; pre-order puts each genre before its albums, post-order after them, with the root last.
- The selection events listed the changes (
+added,-removed), not the full selection. - The Stern-Brocot model computed children only for the expanded nodes: 1/2 and 2/1 under 1/1, and so on.
Common questions
Why doesn't my new node appear in the tree?
You changed the node directly (parent.add(child)) instead of through the model. Use model.insertNodeInto(child, parent, index), which fires the event, then tree.scrollPathToVisible(new TreePath(child.getPath())) to show it.
How do I expand all nodes?
Loop over rows while expanding: for (int i = 0; i < tree.getRowCount(); i++) tree.expandRow(i);. The row count grows as you expand, so the loop reaches every node. Avoid this for very large or infinite trees.
How do I load children lazily, for example from a server?
Implement a TreeModel that fetches children in getChildCount/getChild (caching them), or add a placeholder child and replace it in a TreeWillExpandListener. Fetch slow data in the background and insert the nodes on the EDT.
How do I get the user object of the selected node?
var node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); then node.getUserObject(), checking for null when nothing is selected.
How do I show a checkbox in each node?
Write a TreeCellRenderer that returns a panel with a JCheckBox and a label, keep the checked state in your node objects, and toggle it in a mouse listener using getPathForLocation. A full TreeCellEditor is needed only if keyboard editing of the checkbox matters.
API reference
| Class / method | Purpose |
|---|---|
JTree(model), JTree(root), JTree(root, asksAllowsChildren), setRootVisible, setShowsRootHandles, setEditable | Creating and configuring trees. |
DefaultMutableTreeNode(userObject), add, getUserObject, setUserObject, setAllowsChildren, getPath, getLevel, getDepth | Nodes. |
breadthFirstEnumeration, preorderEnumeration, postorderEnumeration, depthFirstEnumeration, pathFromAncestorEnumeration | Traversals. |
DefaultTreeModel(root), insertNodeInto, removeNodeFromParent, nodeChanged, nodesWereInserted, reload, getPathToRoot, setAsksAllowsChildren | Changing the tree with notification. |
TreePath(Object[]), getLastPathComponent, getPathCount, getParentPath, pathByAddingChild | Paths. |
getSelectionPath, getSelectionPaths, getLastSelectedPathComponent, setSelectionPath, addTreeSelectionListener | Selection. |
TreeSelectionModel.setSelectionMode: SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION, DISCONTIGUOUS_TREE_SELECTION | Selection modes. |
TreeSelectionEvent.getPaths, isAddedPath; TreeExpansionListener, TreeWillExpandListener | Events. |
makeVisible, scrollPathToVisible, expandPath, collapsePath, getRowForPath, getPathForRow | Expansion and rows. |
DefaultTreeCellRenderer.setLeafIcon/setOpenIcon/setClosedIcon, getTreeCellRendererComponent, JTree.setCellRenderer | Rendering. |
TreeModel.getRoot/getChild/getChildCount/getIndexOfChild/isLeaf/valueForPathChanged, TreeModelListener, TreeModelEvent, EventListenerList | Custom models. |
Summary
JTreedisplays aTreeModel.DefaultTreeModelwithDefaultMutableTreeNodes holding user objects covers most needs; hide the root for a forest and choose the leaf criterion withasksAllowsChildren.- The tree identifies nodes by
TreePaths from the root; rows depend on the expansion state, so prefer paths. - Change the structure through the model (
insertNodeInto,removeNodeFromParent,nodeChanged) so the view is notified, and usescrollPathToVisibleto show new nodes. - Enumerate nodes breadth-first, pre-order or post-order; listen to selection, expansion and will-expand events.
- Renderers are reused labels that receive the node object; reset anything you change. A custom
TreeModelpresents existing hierarchical data lazily, even infinite trees, but must fire model events when the data change.
Practice Questions
1. A program adds a child with selectedNode.add(newNode), but the tree does not show it. What is wrong, and what is the fix?
Adding a child directly to a DefaultMutableTreeNode changes the data structure without notifying the tree. Use model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount()), which adds the node and fires a treeNodesInserted event. If the parent is collapsed, also call tree.scrollPathToVisible(new TreePath(model.getPathToRoot(newNode))) so the user sees the new node.
2. Why does JTree work with TreePath objects instead of nodes with parent links?
The TreeModel interface describes a tree with arbitrary objects and does not require them to implement TreeNode or to know their parents; only the model knows how objects are connected. Since the tree cannot ask a node for its parent, it identifies each node by the complete path of objects from the root.
3. Why should code avoid storing row numbers of tree nodes?
A row number is the position of a node among the currently visible nodes. It changes whenever a node above it is expanded or collapsed, or nodes are inserted or removed, and nodes inside collapsed subtrees have no row at all. A stored row number soon refers to a different node. Tree paths stay valid as long as the nodes exist.
4. A custom tree renderer makes the names of folders bold. After scrolling, many files are bold too. Why?
DefaultTreeCellRenderer returns the same label for every node. The renderer sets the bold font for folders but does not restore the plain font for other nodes, so a node rendered after a folder keeps the bold font. The renderer must set the font on every call, choosing bold or plain.
5. When is it better to implement TreeModel directly than to use DefaultTreeModel?
When the data are already organized hierarchically elsewhere (a file system, a document object model, objects connected by references, a database) or are large or even unbounded. A custom model reads children on demand when the user expands a node, so no duplicate tree of nodes has to be built and kept in sync. The price is that you must fire TreeModelEvents yourself when the data change.
Previous: Swing Table Cell Renderers and Editors: Custom Rendering and Editing
Next: Java 2D Rendering Pipeline: Shapes, Paths and Constructive Area Geometry
Related reading
- Swing Table Cell Renderers and Editors: Custom Rendering and Editing
- Swing Tables: JTable, Table Models, Sorting and Filtering
- Swing Dialogs: JOptionPane, Custom Dialogs and JFileChooser
- GridBagLayout and Custom Layout Managers in Swing
- Swing Menus, Toolbars and Tooltips: Mnemonics, Accelerators and Popup Menus

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.