Java Reference
In-Depth Information
Example 10•20: ComponentTree.java (continued)
public int getChildCount(Object node) {
if (node instanceof Container) {
Container c = (Container) node;
return c.getComponentCount();
}
return 0;
}
// Return the specified child of a parent node.
public Object getChild(Object parent, int index) {
if (parent instanceof Container) {
Container c = (Container) parent;
return c.getComponent(index);
}
return null;
}
// Return the index of the child node in the parent node
public int getIndexOfChild(Object parent, Object child) {
if (!(parent instanceof Container)) return -1;
Container c = (Container) parent;
Component[] children = c.getComponents();
if (children == null) return -1;
for(int i = 0; i < children.length; i++) {
if (children[i] == child) return i;
}
return -1;
}
// This method is only required for editable trees, so it is not
// implemented 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
public void addTreeModelListener(TreeModelListener l) {}
public void removeTreeModelListener(TreeModelListener l) {}
}
/**
* A TreeCellRenderer displays each node of a tree. The default renderer
* displays arbitrary Object nodes by calling their toString() method.
* The Component.toString() method returns long strings with extraneous
* information. Therefore, we use this "wrapper" implementation of
* TreeCellRenderer to convert nodes from Component objects to useful
* String values before passing those String values on to the default
* renderer.
**/
static class ComponentCellRenderer implements TreeCellRenderer {
TreeCellRenderer renderer; // The renderer we are a wrapper for
// Constructor: just remember the renderer
public ComponentCellRenderer(TreeCellRenderer renderer) {
this.renderer = renderer;
}
// This is the only TreeCellRenderer method.
// Compute the string to display, and pass it to the wrapped renderer
Search WWH ::




Custom Search