902 Part III: Software Development Using Java
The following example illustrates how to create a tree and handle selections. The
program creates aDefaultMutableTreeNodeinstance labeled “Options.” This is the top
node of the tree hierarchy. Additional tree nodes are then created, and theadd( )method is
called to connect these nodes to the tree. A reference to the top node in the tree is provided
as the argument to theJTreeconstructor. The tree is then provided as the argument to the
JScrollPaneconstructor. This scroll pane is then added to the content pane. Next, a label
is created and added to the content pane. The tree selection is displayed in this label. To
receive selection events from the tree, aTreeSelectionListeneris registered for the tree.
Inside thevalueChanged( )method, the path to the current selection is obtained and
displayed.
// Demonstrate JTree.
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/*
<applet code="JTreeDemo" width=400 height=200>
</applet>
*/
public class JTreeDemo 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() {
// Create top node of tree.
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
// Create subtree of "A".
DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);