Java Reference
In-Depth Information
dual.addSourceElements(
new String[] {"Sixteen", "Seventeen", "Eighteen"});
dual.addSourceElements(
new String[] {"Nineteen", "Twenty", "Thirty"});
frame.add(dual, BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Adding Element-Level Tooltips to List Items
As described in Chapter 4, all Swing components support displaying tooltip text. By calling the
setToolTipText() method of a component, you can display any single text string over that
component. In the case of a JList component (or for that matter, any component that contains
multiple items such as a JTree or JTable ), this single tooltip text string may not be sufficient.
You may wish to display a different tip over each item in a component.
Displaying item-level tips takes a little more work. To display different tooltip text over
each item, you must create a subclass of JList . From within this subclass, you must manually
register the component with the ToolTipManager . This is normally done for you when you call
setToolTipText() . But, because you won't be calling this method, you must manually notify
the manager, as follows:
ToolTipManager.sharedInstance().registerComponent(this);
After you notify the ToolTipManager , the manager will then notify the component when-
ever the mouse moves over the component. This allows you to override the public String
getToolTipText(MouseEvent mouseEvent) method to provide the appropriate tip for the item
under the mouse pointer. Using some kind of Hashtable , HashMap , or Properties list allows you
to map the item the mouse is over to item-specific tooltip text.
public String getToolTipText(MouseEvent event) {
Point p = event.getPoint();
int location = locationToIndex(p);
String key = (String)model.getElementAt(location);
String tip = tipProps.getProperty(key);
return tip;
}
Figure 13-13 shows how the PropertiesList example class demonstrates various tooltips
based on whichever element the mouse pointer is resting over. The complete source for the
example follows in Listing 13-11.
Search WWH ::




Custom Search