Java Reference
In-Depth Information
Figure 4-4.
Tooltip text displayed with custom colors
After the
JToolTip
has been created, you can configure the inherited
JComponent
properties
or any of the properties specific to
JToolTip
, as shown in Table 4-5.
Table 4-5.
JToolTip Properties
Property Name
Data Type
Access
accessibleContext
AccessibleContext
Read-only
component
JComponent
Read-write
tipText
String
Read-write
UI
ToolTipUI
Read-only
UIClassID
String
Read-only
Displaying Positional Tooltip Text
Swing components can even support the display of different tooltip text, depending on where
the mouse pointer is located. This requires overriding the
public boolean contains(int x, int y)
method, which originates from the
Component
class.
For instance, after enhancing the customized
JButton
created in the previous section
(Figure 4-4), the tooltip text will differ, depending on whether or not the mouse pointer is
within 50 pixels from the left edge of the component.
JButton button = new JButton("Hello, World") {
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.setBackground(Color.YELLOW);
tip.setForeground(Color.RED);
return tip;
}
public boolean contains(int x, int y) {
if (x < 50) {
setToolTipText("Got Green Eggs?");
} else {
setToolTipText("Got Ham?");
}
return super.contains(x, y);
}
};