JTree can display data hierarchy using tree.
A JTree consists of nodes.
The top-most node is called 'root'.
Nodes are added using the add()
method.
The leaf nodes and intermediate nodes are displayed with different icons.
A node in JTree is represented by the TreeNode interface.
Java Swing provides an implementation of this interface, the DefaultMutableTreeNode class.
The following program displays a simple list of components of a computer with their hierarchy using this default node implementation.
import java.awt.Container; import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; public class Main { public static void main(String args[]) { final JFrame f = new JFrame("JTree Demo"); Container c = f.getContentPane(); c.setLayout(new FlowLayout()); DefaultMutableTreeNode root = new DefaultMutableTreeNode("Computer"); DefaultMutableTreeNode c1 = new DefaultMutableTreeNode("A"); DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("B"); DefaultMutableTreeNode c3 = new DefaultMutableTreeNode("C"); root.add(c1);/* ww w . ja v a 2 s .c o m*/ root.add(c2); root.add(c3); c1.add(new DefaultMutableTreeNode("1")); c1.add(new DefaultMutableTreeNode("2")); c2.add(new DefaultMutableTreeNode("3")); c2.add(new DefaultMutableTreeNode("4")); c3.add(new DefaultMutableTreeNode("5")); c3.add(new DefaultMutableTreeNode("6")); JTree t = new JTree(root); c.add(t); f.pack(); f.setVisible(true); } }