Search code examples
javaswingawtmultiple-monitors

Fetching coordinates for top left position of top left monitor


I am trying to fetch the coordinates of the top left position in a multimonitor setup for my screen capture program. Here is what I've currently got for the program:

        int dwidth = 0, dheight = 0; //max dimensions of all monitors
    for (GraphicsDevice gd : GraphicsEnvironment
            .getLocalGraphicsEnvironment().getScreenDevices()) {
        if (gd == GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getDefaultScreenDevice()) {
            minx = -width; //My attempt at finding the minimum X value did not work
        }
        dwidth += gd.getDisplayMode().getWidth();
        dheight += gd.getDisplayMode().getHeight();
    }

Basically I want to be able to run my program across all of the monitors. For full code view here: https://gist.github.com/fletchto99/5788659


Solution

  • You can get a list of GraphicDevices from the GraphicsEnvironment. Each GraphicsDevice would represent a screen.

    Now, you have a number of choices...

    You could simply look through the list of GraphicsDevices and simply find the one with the lowest x/y coordinates or you could combine them all into a "virtual screen" and simply extract the top/left coordinates from it.

    For example...

    public static Rectangle getVirtualScreenBounds() {
    
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice lstGDs[] = ge.getScreenDevices();
    
        Rectangle bounds = new Rectangle();
        for (GraphicsDevice gd : lstGDs) {
    
            bounds.add(gd.getDefaultConfiguration().getBounds());
    
        }
    
        return bounds;
    
    }