Home > Back-end >  How do I get the dimensions of each individual screen in Java
How do I get the dimensions of each individual screen in Java

Time:07-05

I need a function that gives me the resolutions of my individual monitors.

I do know that Toolkit.getDefaultToolkit().getScreenSize() gives me the cumulative resolution of all monitors, but to limit the size of some frames I draw I want to know the resolutions of the individual screens.

I tried using GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices() which returns an array of all screens, but I could not find any resolution information in there.

The header of the function should be something like

/**
 * Returns the Dimension of all available screen devices in order of appearance in  
 * GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()
 * 
 * @return the Dimensions of all available screen devices.
 */
public Dimension[] getScreenResolutions() {
    [ . . . ]
}

CodePudding user response:

You need to use GraphicsConfiguration. The documentation shows how to get the screen bounds.

CodePudding user response:

I just found out the same, while Rob Spoor answered, so I'm gonna give a full answer to my question:

GraphicsDevice has a function getDefaultConfiguration() which returns a GraphicsConfiguration which has a getBounds() method which again returns the values as a Rectangle.

An implementation of my function header would therefore be:

/**
 * Returns the Dimension of all available screen devices in order of appearance in  
 * GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()
 * 
 * @return the Dimensions of all available screen devices.
 */
public Dimension[] getScreenResolutions() {
    // step 1: get amount of screens and allocate space
    int deviceAmount = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length;
    Dimension[] dimensions = new Dimension[deviceAmount];
    Rectangle[] rectangles = new Rectangle[deviceAmount];
    // step 2: get values as Rectangle[]
    for (int i = 0; i < deviceAmount; i  ) { 
        rectangles[i] = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[i].getDefaultConfiguration().getBounds();
    }
    // step 3: convert to Dimension[]
    for (int i = 0; i < rectangles.length; i  ) {
        dimensions[i] = new Dimension(r.getWidth(), r.getHeight());
    }
    // step 4: return
    return dimensions;
}
  • Related