Java JTree

A tree is a component that presents a hierarchical view of data. The user can expand or collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class.

JTree(Object obj[])
JTree(Vector<?>v)
JTree(TreeNode tn)

Here, the tree is constructed from the elements in the array obj.
constructs the tree from the elements of the vector v. The tree whose root node is specified by tn specifies the tree.

JTree relies on two models:
1. TreeModel
2. TreeSelectionModel.

A JTree generates a variety of events, but three relate specifically to trees: TreeExpansionEvent, TreeSelectionEvent, and TreeModelEvent. TreeExpansionEvent events occur when a node is expanded or collapsed. A TreeSelectionEvent is generated when the user selects or deselects a node within the tree.

A TreeModelEvent is fired when the data or structure of the tree changes. The listeners for these events are TreeExpansionListener, TreeSelectionListener, and TreeModelListener, respectively. The tree event classes and listener interfaces are packaged in javax.swing.event.

JTree does not provide any scrolling capabilities of its own. Instead, a JTree is typically placed within a JScrollPane. This way, a large tree can be scrolled through a smaller viewport.

General Procedure to use Tree:

1. Create an instance of JTree.
2. Create a JScrollPane and specify the tree as the object to be scrolled.
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane.

Example:

import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class Trees extends JApplet
{
JTree tree;
JLabel jlab;
public void init()
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch(Exception exc)
{
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI()
{
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3);
tree = new JTree(top);
JScrollPane jsp = new JScrollPane(tree);
add(jsp);
jlab = new JLabel();
add(jlab, BorderLayout.SOUTH);
tree.addTreeSelectionListener(new TreeSelectionListener()
{
public void valueChanged(TreeSelectionEvent tse)
{
jlab.setText("Selection is " + tse.getPath());
}
});
}
}