获取javaFX 8中节点的屏幕坐标

时间:2015-08-04 10:51:24

标签: java javafx awt javafx-8 awtrobot

我正在Windows 8.1 64bit上开发一个JavaFX应用程序,带有4GB RAM,JDK版本为8u45 64bit。

我想使用Robot捕获部分屏幕,但问题是我无法获取我要捕获的锚定窗格的屏幕坐标,我不想使用snapshot因为输出质量不好。这是我的代码。

我在这个链接中看到了这个问题 Getting the global coordinate of a Node in JavaFX 还有这个 get real position of a node in 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();
    }
}

1 个答案:

答案 0 :(得分:14)

由于您使用的是本地(非布局)坐标,因此请使用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();
    }
}