Chapter 33. The JTree Class

Much like the JTable and JList, the JTree class consists of a data model and an Observer. One of the easiest ways to build the tree to display is to create a root node, then add child nodes to it, and then add child nodes to each of them as needed. The DefaultMutableTreeNode class is provided as an implementation of the TreeNode interface.

We create the JTree with a root node as its argument.

    root = new DefaultMutableTreeNode("Foods");
    JTree tree = new JTree(root);

Then we add each node to the root and additional nodes to those to any depth. The following program produces a food tree list by category. Note that we use the JxFrame class, derived from JFrame at the beginning of this section.

 public class TreeDemo extends ...

Get Java™ Design Patterns: A Tutorial 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.