Java Reference
In-Depth Information
Working with Tree Tooltips
If you want a tree to display tooltips for the nodes, you must register the component with the
ToolTipManager . If you don't register the component, the renderer will never get the opportunity
to display tooltips. The renderer displays the tip, not the tree, so setting tooltip text for the tree
is ignored. The following line shows how you to register a specific tree with the ToolTipManager .
ToolTipManager.sharedInstance().registerComponent(aTree);
Once you've notified the ToolTipManager that you want the tree to display tooltip text, you
must tell the renderer what text to display. Although you can directly set the text with the
following lines, this results in a constant setting for all nodes.
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)aTree.getCellRenderer();
renderer.setToolTipText("Constant Tool Tip Text");
Instead of providing a constant setting, one alternative is to provide the renderer with a table
of tooltip strings so that the renderer can determine at runtime the string to display as the tooltip
text. The renderer in Listing 17-6 is one such example that relies on a java.util.Dictionary
implementation (like a Hashtable ) to store a mapping from nodes to tooltip text. If a tip exists
for a specific node, the renderer associates the tip with it.
Listing 17-6. Tooltip Cell Renderer
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.util.*;
public class ToolTipTreeCellRenderer implements TreeCellRenderer {
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
Dictionary tipTable;
public ToolTipTreeCellRenderer (Dictionary tipTable) {
this.tipTable = tipTable;
}
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
renderer.getTreeCellRendererComponent(tree, value, selected, expanded,
leaf, row, hasFocus);
if (value != null) {
Object tipKey;
if (value instanceof DefaultMutableTreeNode) {
tipKey = ((DefaultMutableTreeNode)value).getUserObject();
Search WWH ::




Custom Search