Get screen coordinates of a node in javaFX 8
Asked Answered
B

1

7

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();
    }
}
Biotin answered 4/8, 2015 at 10:51 Comment(4)
In what regard is the "output quality" of snapshot bad?Obbard
Sometimes the image isn't sharp.Biotin
have you tried localToScreen()Because local to scene wiill return coordinates within scene which when you put into robot will capture different locationBrynnbrynna
@TomasBisciak I just tried localToScreen() and the image showed the corner of the screen even furtherBiotin
A
18

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();
    }
}
Aloha answered 4/8, 2015 at 12:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.