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