O'Reilly logo

Java™ Design Patterns: A Tutorial by James W. Cooper

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required