A Simple Tree
Before we look at the models supporting the JTree
class, let’s look at a very simple
example of a tree built with some of the various L&Fs (Figure
17-1). The javax.swing.DefaultMutableTreeNode
class serves as our node class. You don’t have to worry
about specifically making a node a leaf. If the node has no references
to other nodes by the time you display it, it’s a leaf.
Figure 17-1. A simple JTree in the Metal, Motif, and Mac L&Fs
This example works by building up a series of unconnected nodes
(using the DefaultMutableTreeNode
class) and then connecting them. As long as we stick to the default
classes provided with the tree package, we can build a regular model out
of our nodes quite quickly. In this example, we build the model based on
an empty root node, and then populate the tree by attaching the other
nodes to the root or to each other. You can also build the tree first,
and then create the model from the root node. Both methods have the same
result. With a valid tree model in place, we can make a real JTree
object and display it.
// TestTree.java // A simple test to see how we can build a tree and populate it // import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; public class TestTree extends JFrame { JTree tree; DefaultTreeModel treeModel; public TestTree( ) { super("Tree Test Example"); setSize(400, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); ...
Get Java Swing, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.