Magercise 2 Prerequisites
Tree Views
Skeleton Code
A JTree
component has a default view for contained
elementsthe String
representation of the object and a
open/closed turner icons for nonleaf nodes. In this magercise, you will
modify the default behavior to display just the string representation. For
nonleaf nodes, you will add "ROOT:
" to the string
displayed. Also, for the selected cell, have the cell background be light
gray.
Tasks:
The TreeRender skeleton contains an inner class
CellRenderer
that implements the TreeCellRenderer
interface. First, create a constructor that creates a JLabel
to
use as a renderer, be sure to make it opaque.
The TreeCellRenderer
interface describes how
a cell is rendered in a tree. It consists of the method
getTreeCellRendererComponent()
.
Implement the getTreeCellRendererComponent()
method, such that
the text of the renderer is the string representation of the object passed
in. For nonleaf nodes, prefix the string with "ROOT:
".
Change the background color to light gray for selected nodes and return the
label used as the renderer.
Modify the constructor for TreePanel
so that its
constructor accepts a TreeCellRenderer
. Then, call
setCellRenderer()
on the tree to change the renderer.
In the TreeRender
constructor, create a
CellRenderer
. You'll need to pass this along to the
TreePanel
constructor that you just modified.
Add the tree cell rendered to the parameter list to the TreePanel
constructor.
Save everything and compile the program. Then run it to see the results.
Where help exists, the task numbers above are linked to the
step-by-step
help page.
Solution
The following JavaTM source files represent a solution to this Magercise:
Copyright © 1998-1999
MageLang Institute.
All Rights Reserved.