- The Tree Control
- Tree Appearance
- The TreeNode Interface
- The MutableTreeNode Interface
- The DefaultMutableTreeNode Class
- The TreePath Class
- What is a Leaf?
- Tree Expansion and Traversal
- Expanding and Collapsing Nodes under Program Control
- Tree Expansion Events
- Making Nodes Visible
- Controlling Node Expansion and Collapse
- Tree Model Events
- Implementation Plan for the File System Control
- File System Tree Control Implementation
- Using the File System Tree Control
- Custom Tree Rendering and Editing
- Customizing the Default Tree Cell Renderer
- ToolTips and Renderers
- Custom Cell Editors
- Controlling Which Nodes Can Be Edited
- Controlling Editability by Subclassing JTree
- Programmatic Control of Editors
- Editing Trees with Custom User Objects
- The valueForPathChanged Method
- The Tree Implementation
- The Cell Editor
- The Cell Renderer
- Summary
Customizing the Default Tree Cell Renderer
The default tree cell renderer is provided by the class DefaultTreeCell-Renderer, which resides in the Swing javax.swing.tree package. You can get a reference to the renderer that is installed in a tree by using the JTree getCellRenderer method and you should verify that this returns a DefaultTreeCellRenderer, then cast it and use the methods shown in Table 10-5 to change its behavior as required. The method works for all of the current look-and-feel implementations, because their tree cell renderers are all derived from DefaultTreeCellRenderer.
Table 105 Default Tree Cell Renderer Customization Methods
Method |
Description |
public void setBackgroundNonSelectionColor(Color) |
Sets the background color used when the node is not selected. |
public void setBackgroundSelectionColor(Color) |
Sets the color in which to draw the background of a selected node. |
public void setBorderSelectionColor(Color) |
Sets the color in which to draw the border of a selected node. There is no method to set the color of the border of a nonselected node because nonselected nodes do not have borders. |
public void setTextNonSelectionColor(Color) |
Determines the color of the text when the node is not selected. |
public void setTextSelectionColor(Color) |
Determines the color of the text when the node is selected. |
public void setFont(Font) |
Sets the font used to render the node's text. |
public void setClosedIcon(Icon) |
Sets the icon displayed when the node's children are not shown. |
public void setOpenIcon(Icon) |
Sets the icon displayed when the node's children are shown. |
public void setLeafIcon(Icon) |
Changes the icon displayed when the node is a leaf. |
Since each tree uses a single renderer to draw every node, changes you make using these methods are effective for the whole tree. Since a different instance of the renderer is used for each tree, changes made in this way apply only to the single tree whose renderer is modified.
For the purposes of illustration, the next example changes the background of the tree to black and uses green text for nonselected items and white text for those that are selected. The background color for selected items will also be changed to gray. The starting point for this tree is TreeExample1, which was created earlier. This tree shows the crews of the Skylab space station and the Apollo lunar landing missions. The code that we added to the main method of the program, which we renamed ModifyRenderer, is shown in Listing 10-4.
Listing 104 Customizing the default tree cell renderer
// Get the tree's cell renderer. If it is a default // cell renderer, customize it. TreeCellRenderer cr = t.getCellRenderer(); if (cr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer dtcr = (DefaultTreeCellRenderer)cr; // Set the various colors dtcr.setBackgroundNonSelectionColor(Color.black); dtcr.setBackgroundSelectionColor(Color.gray); dtcr.setTextSelectionColor(Color.white); dtcr.setTextNonSelectionColor(Color.green); // Finally, set the tree's background color t.setBackground(Color.black); }
You can run this example for yourself using the command:
java JFCBook.Chapter10.ModifyRenderer
The result. If you partly expand the tree, will look something like Figure 1010.
Figure 1010 Customizing the colors of the nodes.
If you look at the code, you'll see that it gets the tree's renderer and checks that it is the renderer from the basic package, or one derived from it. If it is, then the text and background colors are changed. Once these changes are made, all of the nodes in the tree will be drawn with the new settings. This is a simple way to make basic changes to the tree's appearance. To make more radical changes, you need to customize the renderer that draws each node's representation.
Implementing a Customized Renderer
Like the combo box and list controls, each cell of a tree is drawn by a renderer. Tree renderers implement the TreeCellRenderer interface, which has only has one method:
public abstract Component getTreeCellRendererComponent( JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)
In most cases, the most important argument passed by this method is the value, which is the object to be formatted. The renderer is responsible for configuring a Component that represents this value in the tree. In terms of the Metal look-and-feel, this component will take the place of the folder or leaf icon and the descriptive text that appears to the right of it. The remaining arguments may be used to affect the way in which the component is rendered. For example, if the node is expanded, the Metal look-and-feel shows an open folder; if it is a leaf, it displays a sheet of paper. Selected rows usually have a background of a different color, while a row with the focus might be drawn with a colored line around the border.
You've just seen that you can use public methods supplied by Default-TreeCellRenderer to customize it to some extent. Another way to change the way a node is rendered is to subclass the default renderer. The default renderer is actually a subclass of JLabel that also implements the Tree-CellRenderer interface. The DefaultTreeCellRenderer just places the text and icon it is given on the label and, aside from some work that takes place in the paint method to paint the background and border of the cell, most of the rendering code is inherited from JLabel. If you subclass DefaultTreeCellRenderer, you can do such things as changing the color in which the text is rendered by setting the label's attributes directly. The advantage of this is that you can vary these attributes for each individual node if necessary, rather than setting constant values that apply to the whole tree.
The following example illustrates how to make the renderer node-specific by using a different text color and icon for leaf nodes. This example is actually an extension of Listing 10-4, which works by creating and installing a subclass of the default renderer. The code that is changed is highlighted in bold in Listing 10-5.
Listing 105 Installing a customized version of the default tree cell renderer
TreeCellRenderer cr = t.getCellRenderer(); CustomDefaultRenderer dtcr = new CustomDefaultRenderer(); t.setCellRenderer(dtcr); // Set the various colors dtcr.setBackgroundNonSelectionColor(Color.black); dtcr.setBackgroundSelectionColor(Color.gray); dtcr.setTextSelectionColor(Color.white); dtcr.setTextNonSelectionColor(Color.green); // Set the extra attributes for this renderer dtcr.setLeafForeground(Color.yellow); dtcr.setLeafIcon(new ImageIcon( SubClassRenderer.class.getResource( "images/earth.gif"))); // Change the row height t.setRowHeight(0); // Finally, set the tree's background color t.setBackground(Color.black);
In this example, an instance of the new renderer is instantiated and installed using the JTree setCellRenderer method. The customizations that were used in the previous example can still be applied to it because it is derived from the default renderer, but these changes affect every node in the tree. One extra attribute of the custom renderer allows the color used for leaf nodes to be different from that of branch nodes. This attribute is set in the code shown above using the setLeafForeground method which is implemented by the custom renderer. Note also that the setLeafIcon method, inherited from DefaultTreeCellRenderer, is used to install a different icon that will be used only for leaf nodes. The only other change shown here is to set the cell row height using the JTree setRowHeight method, which requires an integer argument. If you supply a positive value, the rows will all be of that height, whereas a zero or negative value causes the tree look-and-feel class to query the renderer for the height of each row as it draws it, which allows variable height rows. This is necessary in this case because the icon used for leafs nodes is not necessarily the same size as that for branch nodes, so the height of each row needs to depend on the requirements of the node that will occupy it.
Core Note
The default row height is determined by the selected look-and-feel. The Metal look-and-feel does not supply a default height, so each row is as high as its renderer makes it. The Motif look-and-feel sets the default row height to 18 pixels and Windows uses 16 pixels as the default.
The custom renderer itself is actually very simpleits only job is to change the way that the JLabel displays its content by manipulating its properties if the node being rendered is a leaf node. The renderer is implemented here as an inner class, but you could make it equally well a freestand-ing object that can be reused. The code is shown in Listing 10-6.
Listing 106 A customized tree cell renderer
// This class is a custom renderer based // on DefaultTreeCellRenderer protected static class CustomDefaultRenderer extends DefaultTreeCellRenderer { public Component getTreeCellRendererComponent( JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { // Allow the original renderer to set up the label Component c = super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus); if (leaf) { // Use a different foreground // color for leaf nodes. if (leafForeground != null) { c.setForeground(leafForeground); } } return c; } public void setLeafForeground(Color color) { this.leafForeground = color; } private Color leafForeground; }
Since the intention is just to change the way in which the label created by the default renderer is configured, the first step in the getTreeCellRendererComponent method is to invoke the corresponding method of the default renderer superclass and let it set up the label as it would normally appear. This arranges for the appropriate text and icon to be installed, based on whether the node is a leaf or not, whether the node is selected, whether it has the focus, and whether it is expanded. Then, if the node being rendered is a leaf, the foreground text color is set to that configured by the application. If this attribute is null, no change is made to the value set by the default renderer. Note that the getTreeCellRendererComponent method determines whether the node is a leaf by using the leaf argument that is supplied to it. If specific behavior were required for expanded nodes or nodes that had the focus, this would also be handled by checking the method argumentnts.
To try this version of the example for yourself, use the command:
java JFCBook.Chapter10.SubClassRenderer
Figure 1011 shows a typical snapshot of this example after some of the leaf nodes have been exposed. You'll notice that the branch nodes are rendered as they were in Figure 1010, but the leaf nodes have an icon that shows the earth as viewed from the moon and the text is yellow.
Figure 1011 Changing text and icon positions using a custom tree renderer.
One problem with creating a new renderer by subclassing DefaultTree-CellRenderer is that it may only work properly if the Metal or Windows look-and-feel is installed. Because of the fact that this example uses the original renderer functionality by invoking the getTreeCellRendererComponent method of its superclass, there might be a problem if it were replacing the Motif look-and-feel, which has its own cell renderer that is derived from DefaultTreeCellRenderer, because we wouldn't be using its specific getTreeCellRendererComponent method. Whether or not this matters depends entirely on what your customization is. You could, of course, implement a subclass for each of the look-and-feels and install the correct one at run time. There is, however, another technique that avoids having to generate more classes that you'll see in "Rendering and Editing Custom Objects." If you can't achieve the effects you need by subclassing the default renderer, you can provide your own by implementing the TreeCellRenderer interface yourself. The technique for doing this is identical to the one used when creating renderers for the JList and JComboBox control, so it isn't repeated here.