Positioning ToolTips

When you use the ToolTipManager to create a custom ToolTip, you specify the coordinates of the ToolTip on the stage. You do this by specifying the values of the x and y parameters of the new ToolTip in the createToolTip() method. These coordinates are relative to the stage. For example, a value of 0,0 creates a ToolTip at the top left corner of the application.

In some cases, you might not know the exact position that you want the ToolTip to be drawn in; instead, you want the location of the ToolTip to be relative to the target component (the component that has a ToolTip on it). In those cases, you can use the location of the target component to calculate the values of these coordinates. For example, if you want the ToolTip to appear to a component’s right, then you set the ToolTip’s x position to be the x position of the component plus the component’s width, plus some other value for an offset.

You also set the value of the ToolTip’s y position to be the same as the target component’s y position to line the two up horizontally.

One way to get the necessary values so that you can calculate the x position of the ToolTip, is to use an event handler. Event objects passed to an event handler can give you the x position of the target component and the width of the target component.

The following example gets the value of the current target’s x, y, and width properties in the focusIn event handler, and uses them to position the ToolTip. In this case, the current target is the TextInput control, and the ToolTip appears to its right with a 10 pixel offset.

The previous example creates a ToolTip on a target component that is not inside any containers. However, in many cases, your components will be inside layout containers such as a VBox or an HBox. Under these circumstances, the coordinates you access in the event handler will be relative to the container and not the main application. But the ToolTipManager expects global coordinates when positioning the ToolTip. This will position ToolTips in unexpected locations.

To avoid this, you can use the contentToGlobal() method to convert the coordinates in the event handler from local to global. All components that subclass UIComponent have this method. It takes a single Point that is relative to the target’s enclosing container as an argument and returns a Point that is relative to the stage.

The following example calls the TextInput control’s contentToGlobal() method to convert the control’s coordinates from those that are relative to the VBox container to global coordinates.

Here’s a ZIP file with the source code from this blog entry.