
Create Custom Tool Tips #43
Chapter 6, Transparent and Animated Windows
|
225
HACK
H A C K
#43
Create Custom Tool Tips
Hack #43
Replace the standard rollover tool tip with an attractive custom version,
including a border and rounded corners.
Every Swing component can have a tool tip, a little snippet of explanatory
text that pops up when you let your mouse cursor linger over the compo-
nent. These tool tips are often useful, but they usually look quite boring.
This hack shows how to create visually interesting tool tips with a custom
subclass.
In Swing, all tool tips are instances of the
JToolTip class. To create your own
version, you need only subclass
JToolTip and override the paintComponent( )
method. In this hack, we’ll create a tool tip with a rectangle that has a bev-
eled border and a white background. The actual drawing can be taken care
of with a few Java2D drawing commands. Example 6-4 is the code to draw
the tool tip’s background and border.
Example 6-4. A nice-looking tool tip
class CustomToolTip extends JToolTip {
public void paintComponent(Graphics g) {
// create a round rectangle
Shape round = new RoundRectangle2D.Float(4,4,
this.getWidth( )-1-8,
this.getHeight( )-1-8,
15,15);
// draw the white background
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.white);
g2.fill(round);
// draw the gray border ...