JavaFX: how to set correct tooltip position?

2020-03-23 18:26发布

问题:

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?

回答1:

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());