Waxren Waxren - 5 months ago 98
Java Question

Get screen coordinates of a node in javaFX 8

I am developing a JavaFX application on Windows 8.1 64bit with 4GB of RAM with JDK version 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.

I have seen the question in this link
Getting the global coordinate of a Node in JavaFX
and this one
get real position of a node in javaFX
and I tried every answer but nothing is working, the image shows different parts of the screen.

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

Answer

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(...):

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