Monday, June 19, 2006

Programmatically show a tool tip in Swing

A better way to do this exists, I am sure, but I failed to find it easily with Google: How to display a tool tip programmatically in Swing:

        new MouseEvent(targetComponent, 0, 0, 0,
                0, 0, // X-Y of the mouse for the tool tip
                0, false));

Note the commented line. This is the relative location of the synthetic mouse event to the target component. The (0, 0) example above is as if the user had paused the mouse at the upper-left corner of the component, and the tool tip displays accordingly.

Another choice might be (targetComponent.getWidth(), targetComponent.getHeight()) for the lower-right corner, etc.

I wish Swing had a more straight-forward way of using the tool tip framework programmatically. I would like to be able to reuse tool tips for form validation. But at least this works.

UPDATE: 4 years on and I still get more positive comments on this post than any other. Hopefully the JDK improves in this area.


cesilko said...

Brian, you saved me hours! :-) I wanted to invoke tooltip on focusGained event but something told me to Google for it. Your blog showed up as the #1. Congrats and thanks a million!

binkley said...


It's very rewarding to hear that my small post made a difference.

And it is quite an ugly hack at that.

Issam said...

Thanks a lot !

Ragha said...

was looking for this since ages...
thx a lot

Srinivasu D said...

Thanks dude... you saved me!

Anonymous said...

Thank you for this! It's pure awesomeness!

Anonymous said...

Thanks for this great hint! I've been searching for such a possibility for hours. It's working great!!

svaens said...

Thanks for pointing me in the right direction.

In the end however, I decided to go more in the direction shown by this blog:

modified it, and ended up with this code, which shows a popup tooltip until you click it away:

private static HashMap toolTipMap = new HashMap();

public static void showToolTip(final JComponent component, String tip, int x, int y)
JToolTip tooltip = toolTipMap.get(component);

if (tooltip==null)
tooltip = component.createToolTip();
toolTipMap.put(component, tooltip);
PopupFactory popupFactory = PopupFactory.getSharedInstance();
final Popup tooltipContainer = popupFactory.getPopup(component, tooltip, x, y);;
tooltip.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)

Sorry about the poor format ... I didn't know if i could use some sort of code formatting here.

Rajeev said...

thanks for sharing this. otherwise it would've taken hours to figure this out...

Anonymous said...


Anonymous said...