JavaFX: how to set correct tooltip position?
Asked Answered
U

2

5

I have a TextField for which I want a Tooltip to be shown under some circumstances.

After performing checks I run the followig code:

textFieldUsername.setTooltip(new Tooltip("Enter username!"));
textFieldUsername.getTooltip().setAutoHide(true);
textFieldUsername.getTooltip().show(textFieldUsername, 1, 1);

So when somebody tries to login with empty username he gets a prompting Tooltip over the "username" TextField.

But when it comes to action, the Tooltip pops up in the top left corner of the screen.

Should I calculate coords of my scene, then add my TextField coords to them, or there is a way to set these 1, 1 arguments from the call of show() to be relative to the TextField position?

Unlikely answered 24/10, 2012 at 12:36 Comment(0)
P
12

I think the coordinates are always relative to the screen. To calculate component coordinates you need to incorporate scene and window coordinates.

Point2D p = label.localToScene(0.0, 0.0);
label.getTooltip().show(label,
        p.getX() + label.getScene().getX() + label.getScene().getWindow().getX(),
        p.getY() + label.getScene().getY() + label.getScene().getWindow().getY());
Pompadour answered 24/10, 2012 at 16:24 Comment(1)
right, as stated in javadoc: "public void show(Node ownerNode, double screenX, double screenY) Shows the popup at the specified x,y location relative to the screen."Puppetry
I
0

JavaFX20: If you want to show it below a component :

tooltip.setOnShown(e -> adjustTooltipPosition(tooltip, component));

// Ensure the tooltip also hides after the mouse moves from the component directly on the popup and exits it
// because it then doesn't recognize a mouse exited event from the component
tooltip.getScene().setOnMouseExited(event -> tooltip.hide());

private void adjustTooltipPosition(Tooltip tooltip, Node component) {
    Bounds bounds = component.localToScreen(component.getBoundsInLocal());
    double x = bounds.getMinX();
    double y = bounds.getMaxY();
    Window window = tooltip.getScene().getWindow();
    /* .tooltip {
        -fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.6), 2.0, -2.0, 2.0, 2.0); 
    } */ 
    // With a nice and smooth shadow on the tooltip window, we need to compensate for its width by 2 now,
    // because the internal process extends the outer stage width of the popup (transparent insets where the shadow is cast). 
    // Without this compensation, it would continuously trigger mouse entered events.
    window.setX(x - 2);
    window.setY(y + 2);
}
Isleana answered 3/7, 2024 at 2:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.