Java Reference
In-Depth Information
Querying Node Relationships
The
DefaultMutableTreeNode
class provides several ways to determine the relationship between
two nodes. In addition, you can check to see if two nodes share a common parent using the
following methods:
•
isNodeAncestor(TreeNode aNode)
: Returns
true
if
aNode
is the current node or a parent of
the current node. This recursively checks
getParent()
until
aNode
or
null
is found.
•
isNodeChild(TreeNode aNode)
: Returns
true
if the current node is the parent of
aNode
.
•
isNodeDescendant(DefaultMutableTreeNode aNode)
: Returns
true
if the current node is
aNode
or an ancestor of
aNode
.
•
isNodeRelated(DefaultMutableTreeNode aNode)
: Returns
true
if both the current node
and
aNode
share the same root (are in the same tree).
•
isNodeSibling(TreeNode aNode)
: Returns
true
if both nodes share the same parent.
Each method returns a
boolean
value, indicating whether or not the relationship exists.
If two nodes are related, you can ask for the root of the tree to find a shared ancestor.
However, this ancestor might not be the closest ancestor within the tree. If a common
node exists lower down in the tree, you can use the
public TreeNode getSharedAncestor
(DefaultMutableTreeNode aNode)
method to find this closer ancestor. If none exists because
the two nodes aren't in the same tree,
null
is returned.
■
Note
If a node asks for the shared ancestor of that node and itself, the shared ancestor is the node itself.
In other words, a node's closest ancestor to itself is itself.
Traversing Trees
The
TreeNode
interface and
DefaultMutableTreeNode
class provide several means of traveling to
all the nodes below a specific node. Given a specific
TreeNode
, you can walk to each descendant
node by going through the
children()
of each node, including the initial node. Given a specific
DefaultMutableTreeNode
, you can find all the descendants by following both
getNextNode()
and
getPreviousNode()
methods until no additional nodes are found. The following code frag-
ment demonstrates the use of the
children()
method of
TreeNode
to traverse an entire tree,
given a starting node.
public void printDescendants(TreeNode root) {
System.out.println(root);
Enumeration children = root.children();
if (children != null) {
while(children.hasMoreElements()) {
printDescendants((TreeNode)children.nextElement());
}
}
}