/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Component;
import java.util.Dictionary;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.ToolTipManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellRenderer;
public class TreeTips {
public static void main(String args[]) {
JFrame frame = new JFrame("Tree Tips");
Properties props = System.getProperties();
JTree tree = new JTree(props);
ToolTipManager.sharedInstance().registerComponent(tree);
TreeCellRenderer renderer = new ToolTipTreeCellRenderer(props);
tree.setCellRenderer(renderer);
JScrollPane scrollPane = new JScrollPane(tree);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
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();
} else {
tipKey = tree.convertValueToText(value, selected, expanded,
leaf, row, hasFocus);
}
Object tip = tipTable.get(tipKey);
if (tip != null) {
renderer.setToolTipText(tip.toString());
} else {
renderer.setToolTipText(null);
}
}
return renderer;
}
}
|