Java Reference
In-Depth Information
If you don't like working with the
UIManager
or just want to change the icons, font, or colors
for a single tree, you don't need to create a custom tree cell renderer. Instead, you can ask the
tree for its renderer and customize it to display the icons, font, or colors you want. Figure 17-8
shows a
JTree
with an altered renderer. Instead of creating a new renderer, the existing default
renderer was customized with the following source:
JTree tree = new JTree();
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)tree.getCellRenderer();
// Swap background colors
Color backgroundSelection = renderer.getBackgroundSelectionColor();
renderer.setBackgroundSelectionColor(renderer.getBackgroundNonSelectionColor());
renderer.setBackgroundNonSelectionColor(backgroundSelection);
// Swap text colors
Color textSelection = renderer.getTextSelectionColor();
renderer.setTextSelectionColor(renderer.getTextNonSelectionColor());
renderer.setTextNonSelectionColor(textSelection);
Figure 17-8.
A JTree with an altered default renderer
Remember that
TreeUI
caches renderer size information. If a change to the renderer
changes the renderer size, this cache isn't updated. To get around the problem, it's necessary
to signal to the tree that the cache is invalid. One such signal is to change the
rowHeight
prop-
erty. As long as the current
rowHeight
property setting isn't positive, the
TreeUI
must ask the
renderer for its height. Therefore, decreasing the value by 1 has a side effect of invalidating the
cached renderer size information, causing the tree to be displayed with the proper initial sizes
for all the renderers. Adding the following source to the previous example demonstrates this.
renderer.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 32));
int rowHeight = tree.getRowHeight();
if (rowHeight <= 0) {
tree.setRowHeight(rowHeight - 1);
}
The window on the left in Figure 17-9 shows the effect this addition has on Figure 17-8.
If you didn't change the
rowHeight
property to invalidate the display cache, you would get the
effect shown in the right window instead.