X 很好,但奇怪的是 Y 移动了几个像素
Popup resultsList = new Popup();
Bounds textFieldBounds = textField.localToScene(textField.getBoundsInLocal());
ListView lsv = new ListView();
lsv.layoutXProperty().set(0);
lsv.layoutYProperty().set(0);
resultsList.getContent().add(lsv);
Window window = textField.getScene().getWindow();
double x = window.getX();
double y = window.getY();
resultsList.show(textField,
x + textFieldBounds.getMinX(), y + textFieldBounds.getMaxY());
到目前为止有人遇到过这个问题吗?
最佳答案
您将获取文本字段相对于场景的边界,然后添加窗口的坐标。因此,窗口坐标和场景坐标之间的任何差异(例如标题栏的大小)都会导致您的偏移。
使用
Bounds boundsInScreen = textField.localToScreen(textField.getBoundsInLocal());
resultsList.show(textField, boundsInScreen.getMinX(), boundsInScreen.getMaxY());
你也可以这样做
// your existing code
double sceneX = textField.getScene().getX();
double sceneY = textField.getScene().getY();
resultsList.show(textField, x + textFieldBounds.getMinX() + sceneX,
y + textFieldBounds.getMaxY() + sceneY);
但当然第一个版本不太冗长。
关于java - 获取控件的全局屏幕坐标时 Y 坐标不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33022072/