The following example illustrates how to create a tree and handle selections. The
program creates a DefaultMutableTreeNode instance labeled "Options." This is the top
node of the tree hierarchy. Additional tree nodes are then created, and the add( ) 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 the JTree constructor. The tree is then provided as the argument to the
JScrollPane constructor. 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, a TreeSelectionListener is registered for the tree.
Inside the valueChanged( ) 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);
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home