Java Reference
In-Depth Information
This leaves but one question: How do you get the starting node? Well, the first node could
be selected as the result of a user action, or you can ask a tree's
TreeModel
for its root node.
You'll explore
TreeModel
shortly, but the source to get the root node follows. Because
TreeNode
is only one possible type of object that can be stored in a tree, the
getRoot()
method of
TreeModel
returns an
Object
.
TreeModel model = tree.getModel();
Object rootObject = model.getRoot();
if ((rootObject != null) && (rootObject instanceof DefaultMutableTreeNode)) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode)rootObject;
...
}
■
Note
I can think of only one reason why you would want to create a replacement to the
TreeNode
interface
to describe the basic requirements of a node in a
JTree
: if you want to use an
Iterator
from the new Java
Collections API, instead of an
Enumeration
to return a list of children, you can create your own replacement
to
TreeNode
. This isn't recommended, however.
JTree.DynamicUtilTreeNode Class
The
JTree
class includes an inner class,
JTree.DynamicUtilTreeNode
, which the tree uses to
help create the nodes for your trees. The
DynamicUtilTreeNode
is a
DefaultMutableTreeNode
subclass that doesn't create its child nodes until they're needed. The child nodes are needed
when you either expand the parent node or try to traverse a tree. Although you normally
wouldn't use this class directly, you might find a place for it. To demonstrate, the following
example uses a
Hashtable
to create the nodes for a tree. Instead of having an invisible node at
the root of the tree (with a
userObject
property setting of
root
), the root node will have a property
of
"Root"
.
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
Hashtable hashtable = new Hashtable();
hashtable.put ("One", args);
hashtable.put ("Two", new String[]{"Mercury", "Venus", "Mars"});
Hashtable innerHashtable = new Hashtable();
Properties props = System.getProperties();
innerHashtable.put (props, props);
innerHashtable.put ("Two", new String[]{"Mercury", "Venus", "Mars"});
hashtable.put ("Three", innerHashtable);
JTree.DynamicUtilTreeNode.createChildren(root, hashtable);
JTree tree = new JTree(root);
The code just listed creates a tree with the same nodes as shown earlier in the
TreeArraySample
program in Figure 17-2. However, the nodes at the first level of the tree are in a different order.
That's because the nodes are in a
Hashtable
in this example, instead of in a
Vector
as in the
TreeArraySample
. The first-level tree elements are added in the order returned by an
Enumeration
of
Hashtable
, instead of being in the order added to the
Vector
, as Figure 17-19 shows.