Trees
One
of Swing’s advanced components is
JTree. Trees are good for representing
hierarchical information, like the contents of a disk drive or a
company’s organizational chart. As with all Swing components,
the data model is
distinct from the visual representation. This means you can do things
like update the data model and trust that the visual component will
be updated properly.
JTree is powerful and complex. It’s so
complicated, in fact, that the classes that support
JTree have their own package,
javax.swing.tree
. However, if you accept the defaults
options for almost everything, JTree is very easy
to use. Figure 15.6 shows a JTreerunning in a Swing application that we’ll describe a
little later.

Figure 15-6. The JTree class in action
Nodes and Models
A tree’s data model is made up of interconnected nodes. A node has a name, typically, a parent, and some number of children (possibly 0). In Swing, a node is represented by the TreeNode interface. Nodes that can be modified are represented by MutableTreeNode. A concrete implementation of this interface is DefaultMutableTreeNode. One node, called the root node, usually resides at the top of the hierarchy.
A tree’s data model is represented by the TreeModel
interface. Swing provides an
implementation of this interface called
DefaultTreeModel
.
You can create a DefaultTreeModel by passing a
root TreeNode to its constructor.
You could ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access