Java Reference
In-Depth Information
Example 19−5: DOMTreeWalkerTreeModel.java (continued)
* Create a TreeModel for a TreeWalker that returns the specified
* element and all of its descendant nodes.
**/
public DOMTreeWalkerTreeModel(Element element) {
DocumentTraversal dt = (DocumentTraversal)element.getOwnerDocument();
walker = dt.createTreeWalker(element, NodeFilter.SHOW_ALL, null,false);
}
// Return the root of the tree
public Object getRoot() { return walker.getRoot(); }
// Is this node a leaf? (Leaf nodes are displayed differently by JTree)
public boolean isLeaf(Object node) {
walker.setCurrentNode((Node)node); // Set current node
Node child = walker.firstChild();
// Ask for a child
return (child == null);
// Does it have any?
}
// How many children does this node have?
public int getChildCount(Object node) {
walker.setCurrentNode((Node)node); // Set the current node
// TreeWalker doesn't count children for us, so we count ourselves
int numkids = 0;
Node child = walker.firstChild();
// Start with the first child
while(child != null) {
// Loop 'till there are no more
numkids++;
// Update the count
child = walker.nextSibling();
// Get next child
}
return numkids;
// This is the number of children
}
// Return the specified child of a parent node.
public Object getChild(Object parent, int index) {
walker.setCurrentNode((Node)parent); // Set the current node
// TreeWalker provides sequential access to children, not random
// access, so we've got to loop through the kids one by one
Node child = walker.firstChild();
while(index-- > 0) child = walker.nextSibling();
return child;
}
// Return the index of the child node in the parent node
public int getIndexOfChild(Object parent, Object child) {
walker.setCurrentNode((Node)parent);
// Set current node
int index = 0;
Node c = walker.firstChild();
// Start with first child
while((c != child) && (c != null)) {
// Loop 'till we find a match
index++;
c = walker.nextSibling();
// Get the next child
}
return index;
// Return matching position
}
// Only required for editable trees; unimplemented here.
public void valueForPathChanged(TreePath path, Object newvalue) {}
// This TreeModel never fires any events (since it is not editable)
// so event listener registration methods are left unimplemented
Search WWH ::




Custom Search