java 在 javaFX 8 中获取节点的屏幕坐标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31807329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get screen coordinates of a node in javaFX 8
提问by Waxren
I am developing a JavaFX application on Windows 8.1 64bit with 4GB of RAM with JDK version 8u45 64bit.
我正在 Windows 8.1 64bit 上开发 JavaFX 应用程序,带有 4GB RAM 和 JDK 版本 8u45 64bit。
I want to capture part of the screen using Robot
but the problem is that I can't get the screen coordinates of the anchor pane that I want to capture and I don't want to use snapshot
because the output quality is bad. Here is my code.
我想使用捕获屏幕的一部分,Robot
但问题是我无法获得我想要捕获的锚窗格的屏幕坐标,我不想使用,snapshot
因为输出质量很差。这是我的代码。
I have seen the question in this link Getting the global coordinate of a Node in JavaFXand this one get real position of a node in javaFXand I tried every answer but nothing is working, the image shows different parts of the screen.
我在这个链接中看到了这个问题, 在 JavaFX 中获取节点的全局坐标,这个 在 javaFX 中获取节点的真实位置,我尝试了每个答案,但没有任何效果,图像显示了屏幕的不同部分。
private void capturePane() {
try {
Bounds bounds = pane.getLayoutBounds();
Point2D coordinates = pane.localToScene(bounds.getMinX(), bounds.getMinY());
int X = (int) coordinates.getX();
int Y = (int) coordinates.getY();
int width = (int) pane.getWidth();
int height = (int) pane.getHeight();
Rectangle screenRect = new Rectangle(X, Y, width, height);
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "png", new File("image.png"));
} catch (IOException | AWTException ex) {
ex.printStackTrace();
}
}
回答by James_D
Since you are starting with local (not layout) coordinates, use getBoundsInLocal()
instead of getLayoutBounds()
. And since you are wanting to transform to screen (not scene) coordinates, use localToScreen(...)
instead of localToScene(...)
:
由于您从本地(而非布局)坐标开始,请使用getBoundsInLocal()
代替getLayoutBounds()
。并且由于您要转换为屏幕(而不是场景)坐标,请使用localToScreen(...)
代替localToScene(...)
:
private void capturePane() {
try {
Bounds bounds = pane.getBoundsInLocal();
Bounds screenBounds = pane.localToScreen(bounds);
int x = (int) screenBounds.getMinX();
int y = (int) screenBounds.getMinY();
int width = (int) screenBounds.getWidth();
int height = (int) screenBounds.getHeight();
Rectangle screenRect = new Rectangle(x, y, width, height);
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "png", new File("image.png"));
} catch (IOException | AWTException ex) {
ex.printStackTrace();
}
}