Java Reference
In-Depth Information
When
JTree
gets a
Vector
as its constructor argument, the tree creates a
DefaultMutableTreeNode
for the root node, and then creates another one for each element in
the
Vector
, making each element node a child of the root node. The data for the root node
unfortunately is not the
"Root"
you specify, but rather
root
, and isn't shown.
If, instead, you wanted to use
DefaultMutableTreeNode
to manually create the nodes of a
tree, or if you wanted to display the root node, a few more lines would be necessary, as follows:
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode mercury = new DefaultMutableTreeNode("Mercury");
root.insert(mercury, 0);
DefaultMutableTreeNode venus = new DefaultMutableTreeNode("Venus");
root.insert(venus, 1);
DefaultMutableTreeNode mars = new DefaultMutableTreeNode("Mars");
root.insert(mars, 2);
JTree tree = new JTree(root);
Besides using the
insert()
method from
MutableTreeNode
to associate a child with a parent,
DefaultMutableTreeNode
has an
add()
method that automatically adds a child node at the end,
without providing an index.
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode mercury = new DefaultMutableTreeNode("Mercury");
root.add(mercury);
DefaultMutableTreeNode venus = new DefaultMutableTreeNode("Venus");
root.add(venus);
DefaultMutableTreeNode mars = new DefaultMutableTreeNode("Mars");
root.add(mars);
JTree tree = new JTree(root);
Both of the previous blocks of source create a tree like the one shown in Figure 17-17.
Figure 17-17.
Using DefaultMutableTreeNode
If you don't need a root node and want the same behavior as if you had used
NamedVector
at the root of a tree, you could do the following, too:
String elements[] = { "Mercury", "Venus", "Mars"} ;
JTree tree = new JTree(elements);