Java Reference
In-Depth Information
instead of the first, requires you to ask the node with
getChildCount()
how many children it
already has and then add 1:
mutableTreeNode.insert(childMutableTreeNode, mutableTreeNode.getChildCount()+1);
At least for the
DefaultMutableTreeNode
class described next,
setParent()
sets a node to be
the parent of a child node, even though it doesn't make the child node a child of the parent. In
other words, don't call
setParent()
yourself; call
insert()
, and it will set the parent accordingly.
■
Caution
The
insert()
method doesn't allow circular ancestry, where the child node to be added is an
ancestor to the parent. If that's attempted, an
IllegalArgumentException
will be thrown.
DefaultMutableTreeNode Class
The
DefaultMutableTreeNode
class provides an implementation of the
MutableTreeNode
interface
(which implements the
TreeNode
interface). When you're creating a tree from a
Hashtable
, an
array, or a
Vector
constructor,
JTree
automatically creates the nodes as a set of type
DefaultMutableTreeNode
. If, on the other hand, you want to create the nodes yourself, you need
to create one instance of type
DefaultMutableTreeNode
for every node in your tree.
Creating a DefaultMutableTreeNode
Three constructors are available for creating instances of
DefaultMutableTreeNode
:
public DefaultMutableTreeNode()
DefaultMutableTreeNode node = new DefaultMutableTreeNode();
public DefaultMutableTreeNode(Object userObject)
DefaultMutableTreeNode node = new DefaultMutableTreeNode("Node");
public DefaultMutableTreeNode(Object userObject, boolean allowsChildren)
DefaultMutableTreeNode node = new DefaultMutableTreeNode("Node", false);
The information stored at every node is called the
user object
. When not specified by one
of the constructors, this user object is
null
. In addition, you can specify whether a node is
allowed to have children.
Building DefaultMutableTreeNode Hierarchies
Building a hierarchy of nodes of type
DefaultMutableTreeNode
requires creating an instance
of type
DefaultMutableTreeNode
, creating nodes for its children, and then connecting them.
Before using
DefaultMutableTreeNode
directly to create the hierarchy, first let's see how to use
the new
NamedVector
class to create a tree with four nodes: one root and three leaf nodes.
Vector vector = new NamedVector("Root", new String[]{ "Mercury", "Venus", "Mars"} );
JTree tree = new JTree(vector);