How do I control the display of a JComponent's Tooltip?

I have a JComponent that's painting various shapes on itself. I'm detecting whenever the mouse enters one of these shapes and changing the tooltip accordingly.

The problems I'm having are:

  • The tooltip doesn't follow the mouse as the user tracks the mouse across the shape. It stays where it was first set and then only jumps whenever another shape changes the tooltip.
  • It takes about a second for the tooltip to appear, but I'd like it to appear immediately.

Can someone suggest a way of getting these behaviours without writing a custom tooltip mechanism?

Asked by: Melissa719 | Posted: 21-01-2022

Answer 1

Take a look at the ToolTipManager.

You can register your component with that manager and then adjust a number of settings. Its pretty straight forward to use.

That at least can solve your initialdelay problem.

For your first problem you can overide the createTooltip command from your component to get a hold of the JTooltip instance. and then its easy make the position change whenever you move your mouse(aka follow your mouse) as its a subclass of the JComponent class.

Answered by: Agata118 | Posted: 22-02-2022

Answer 2

To solve your first issue of where the tooltip doesn't follow the mouse, if you override the getToolTipLocation(MouseEvent e) in JComponent, you can return the point for where you want to the display the tooltip. The MouseEvent will allow you to retrieve the x and y.

Answered by: Rafael463 | Posted: 22-02-2022

Similar questions

java - Determining a JComponent's immediate neighbors in a FlowLayout

I have a JPanel that uses a FlowLayout and contains many JButtons. The buttons are in a 2-dimensional grid (by the FlowLayout). The JPanel can be resized, and, of course, when it is, the location of the buttons in the grid changes (although the order, of course, stays the same). I want the user to be able to navigate from one button to another in the grid by using the arrow keys on the keyboard. Is there a way t...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)