163

How can one get the screen resolution (width x height) in pixels?

I am using a JFrame and the java swing methods.

AndreDurao
  • 5,600
  • 7
  • 41
  • 61
  • 2
    can you provide some more detail about what you question.One liner can lead to hundred different ways. – Anil Vishnoi Sep 09 '10 at 20:17
  • 8
    I guess you don't care about multiple monitor setups. It seems many application developers ignore these. Everyone uses multiple monitors where I work, so we always have to think about them. We probe all of the monitors and set them up as screen objects so that we can target them when we open up new frames. If you really don't need this functionality, then I guess it's okay that you asked such an open-ended question and accepted an answer so quickly. – Erick Robertson Sep 09 '10 at 20:50

12 Answers12

311

You can get the screen size with the Toolkit.getScreenSize() method.

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();

On a multi-monitor configuration you should use this :

GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();

If you want to get the screen resolution in DPI you'll have to use the getScreenResolution() method on Toolkit.


Resources :

Devon_C_Miller
  • 16,248
  • 3
  • 45
  • 71
Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
  • 10
    This doesn't work for me. I have a 3840x2160 monitor, but `getScreenSize` returns 1920x1080. – ZhekaKozlov Mar 01 '18 at 10:25
  • I am using windows 10, with 1920 * 1080 but it returns 1280 * 720. Also is tthere a way to change the resolution using toolkit? – prachi Nov 17 '21 at 06:44
  • @prachi well I think it's because you're using a lower resolution (or higher scaling on windows specifically) than what your screen actually is. You can try the solution I gave, it computes the total screen real-estate for any number of screens, without using the inconsistent `Toolkit#getScreenSize()`. – Lorenzo Jun 28 '22 at 19:10
17

This code will enumerate the graphics devices on the system (if multiple monitors are installed), and you can use that information to determine monitor affinity or automatic placement (some systems use a little side monitor for real-time displays while an app is running in the background, and such a monitor can be identified by size, screen colors, etc.):

// Test if each monitor will support my app's window
// Iterate through each monitor and see what size each is
GraphicsEnvironment ge      = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[]    gs      = ge.getScreenDevices();
Dimension           mySize  = new Dimension(myWidth, myHeight);
Dimension           maxSize = new Dimension(minRequiredWidth, minRequiredHeight);
for (int i = 0; i < gs.length; i++)
{
    DisplayMode dm = gs[i].getDisplayMode();
    if (dm.getWidth() > maxSize.getWidth() && dm.getHeight() > maxSize.getHeight())
    {   // Update the max size found on this monitor
        maxSize.setSize(dm.getWidth(), dm.getHeight());
    }

    // Do test if it will work here
}
Rick Hodgin
  • 657
  • 2
  • 8
  • 15
12

This call will give you the information you want.

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Starkey
  • 9,673
  • 6
  • 31
  • 51
  • 1
    This will only give the dimensions of the primary display on a multi-monitor system. See https://docs.oracle.com/javase/8/docs/api/java/awt/Toolkit.html#getScreenSize-- – Nathan Dec 24 '18 at 15:12
5

Unfortunately Toolkit.getDefaultToolkit() does not help if you have multiple displays, and on Windows it also reports scaled values if you have changed font setting "Scale and Layout" from 100%. For example at 150% font scale my 1920x1080 screen is reported as 1280x720 which (unhelpfully) changes the resolution my app uses.

You can access all details of the screen devices under:

GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();

// Windows scaled sizes (eg 1280x720 for my case at 150% scaling)
Rectangle bounds = devices[nnn].getDefaultConfiguration().getBounds();

// Display sizes (same as above at 100% scale, 1920x1080 for my case)
DisplayMode dm = devices[nnn].getDefaultConfiguration().getDevice().getDisplayMode();
Rectangle orig = new Rectangle((int)bounds.getX(), (int)bounds.getY(), dm.getWidth(), dm.getHeight());

I use this method which reads the default display modes of each GraphicsDevice to access the original screen position+dimensions, and returns set of rectangles sorted in left->right X position order per screen:

/** Get actual screen display sizes, ignores Windows font scaling, sort left to right */
public static List<Rectangle> getDisplays() {
  return Arrays.stream(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices())
     .map(GraphicsDevice::getDefaultConfiguration)
     // For scaled sizes use .map(GraphicsConfiguration::getBounds) instead of:
     .map(c -> {
            var dm = c.getDevice().getDisplayMode();
            var bounds = c.getBounds();
            return new Rectangle((int)bounds.getX(), (int)bounds.getY(), dm.getWidth(), dm.getHeight());
      })
     .sorted(Comparator.comparing(Rectangle::getX))
     .toList();
}

The above code runs under Windows and WSL. If you wish to have a version which returns the scaled values, just switch the commented out line above.

DuncG
  • 12,137
  • 2
  • 21
  • 33
  • This information really saved my day! Scaling is now a very popular option in Windows so I don't understand why other solutions did not mention it! – paulo116 Oct 29 '22 at 13:51
4

Here's some functional code (Java 8) which returns the x position of the right most edge of the right most screen. If no screens are found, then it returns 0.

  GraphicsDevice devices[];

  devices = GraphicsEnvironment.
     getLocalGraphicsEnvironment().
     getScreenDevices();

  return Stream.
     of(devices).
     map(GraphicsDevice::getDefaultConfiguration).
     map(GraphicsConfiguration::getBounds).
     mapToInt(bounds -> bounds.x + bounds.width).
     max().
     orElse(0);

Here are links to the JavaDoc.

GraphicsEnvironment.getLocalGraphicsEnvironment()
GraphicsEnvironment.getScreenDevices()
GraphicsDevice.getDefaultConfiguration()
GraphicsConfiguration.getBounds()

Nathan
  • 8,093
  • 8
  • 50
  • 76
4

These three functions return the screen size in Java. This code accounts for multi-monitor setups and task bars. The included functions are: getScreenInsets(), getScreenWorkingArea(), and getScreenTotalArea().

Code:

/**
 * getScreenInsets, This returns the insets of the screen, which are defined by any task bars
 * that have been set up by the user. This function accounts for multi-monitor setups. If a
 * window is supplied, then the the monitor that contains the window will be used. If a window
 * is not supplied, then the primary monitor will be used.
 */
static public Insets getScreenInsets(Window windowOrNull) {
    Insets insets;
    if (windowOrNull == null) {
        insets = Toolkit.getDefaultToolkit().getScreenInsets(GraphicsEnvironment
                .getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration());
    } else {
        insets = windowOrNull.getToolkit().getScreenInsets(
                windowOrNull.getGraphicsConfiguration());
    }
    return insets;
}

/**
 * getScreenWorkingArea, This returns the working area of the screen. (The working area excludes
 * any task bars.) This function accounts for multi-monitor setups. If a window is supplied,
 * then the the monitor that contains the window will be used. If a window is not supplied, then
 * the primary monitor will be used.
 */
static public Rectangle getScreenWorkingArea(Window windowOrNull) {
    Insets insets;
    Rectangle bounds;
    if (windowOrNull == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        insets = Toolkit.getDefaultToolkit().getScreenInsets(ge.getDefaultScreenDevice()
                .getDefaultConfiguration());
        bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    } else {
        GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
        insets = windowOrNull.getToolkit().getScreenInsets(gc);
        bounds = gc.getBounds();
    }
    bounds.x += insets.left;
    bounds.y += insets.top;
    bounds.width -= (insets.left + insets.right);
    bounds.height -= (insets.top + insets.bottom);
    return bounds;
}

/**
 * getScreenTotalArea, This returns the total area of the screen. (The total area includes any
 * task bars.) This function accounts for multi-monitor setups. If a window is supplied, then
 * the the monitor that contains the window will be used. If a window is not supplied, then the
 * primary monitor will be used.
 */
static public Rectangle getScreenTotalArea(Window windowOrNull) {
    Rectangle bounds;
    if (windowOrNull == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    } else {
        GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
        bounds = gc.getBounds();
    }
    return bounds;
}
BlakeTNC
  • 941
  • 11
  • 14
3

This is the resolution of the screen that the given component is currently assigned (something like most part of the root window is visible on that screen).

public Rectangle getCurrentScreenBounds(Component component) {
    return component.getGraphicsConfiguration().getBounds();
}

Usage:

Rectangle currentScreen = getCurrentScreenBounds(frameOrWhateverComponent);
int currentScreenWidth = currentScreen.width // current screen width
int currentScreenHeight = currentScreen.height // current screen height
// absolute coordinate of current screen > 0 if left of this screen are further screens
int xOfCurrentScreen = currentScreen.x

If you want to respect toolbars, etc. you'll need to calculate with this, too:

GraphicsConfiguration gc = component.getGraphicsConfiguration();
Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
jan
  • 2,741
  • 4
  • 35
  • 56
2
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
framemain.setSize((int)width,(int)height);
framemain.setResizable(true);
framemain.setExtendedState(JFrame.MAXIMIZED_BOTH);
2

Here is a snippet of code I often use. It returns the full available screen area (even on multi-monitor setups) while retaining the native monitor positions.

public static Rectangle getMaximumScreenBounds() {
    int minx=0, miny=0, maxx=0, maxy=0;
    GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    for(GraphicsDevice device : environment.getScreenDevices()){
        Rectangle bounds = device.getDefaultConfiguration().getBounds();
        minx = Math.min(minx, bounds.x);
        miny = Math.min(miny, bounds.y);
        maxx = Math.max(maxx,  bounds.x+bounds.width);
        maxy = Math.max(maxy, bounds.y+bounds.height);
    }
    return new Rectangle(minx, miny, maxx-minx, maxy-miny);
}

On a computer with two full-HD monitors, where the left one is set as the main monitor (in Windows settings), the function returns

java.awt.Rectangle[x=0,y=0,width=3840,height=1080]

On the same setup, but with the right monitor set as the main monitor, the function returns

java.awt.Rectangle[x=-1920,y=0,width=3840,height=1080]
Myrka
  • 63
  • 5
2

There's many answers but I still feel they're not adequate enough, my approach computes global variables related to the screen size once and also using a single loop of all the monitors:

public final class ScreenArea {
    public static final Rectangle RECTANGLE;
    public static final int 
        LEFT, RIGHT, 
        TOP, BOTTOM, 
        MIN_WIDTH, MAX_WIDTH, 
        MIN_HEIGHT, MAX_HEIGHT, 
        TOTAL_WIDTH, TOTAL_HEIGHT;
    
    static {
        // Initialise local vars
        int left, right, top, bottom, minWidth, maxWidth, minHeight, maxHeight;
        left = top = minWidth = minHeight = Integer.MAX_VALUE;
        right = bottom = maxWidth = maxHeight = Integer.MIN_VALUE;
        // In a single loop process all bounds
        Rectangle bounds;
        for (GraphicsDevice device : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
            bounds = device.getDefaultConfiguration().getBounds();
            if (left > bounds.x)
                left = bounds.x;
            if (right < bounds.x + bounds.width)
                right = bounds.x + bounds.width;
            if (top > bounds.y)
                top = bounds.y;
            if (bottom < bounds.y + bounds.height)
                bottom = bounds.y + bounds.height;
            if (minWidth > bounds.width)
                minWidth = bounds.width;
            if (maxWidth < bounds.width)
                maxWidth = bounds.width;
            if (minHeight > bounds.height)
                minHeight = bounds.height;
            if (maxHeight < bounds.height)
                maxHeight = bounds.height;
        }
        TOTAL_WIDTH = right - left;
        TOTAL_HEIGHT = bottom - top;
        RECTANGLE = new Rectangle(TOTAL_WIDTH, TOTAL_HEIGHT);
        // Transfer local to immutable global vars
        LEFT = left; RIGHT = right; TOP = top; BOTTOM = bottom;
        MIN_WIDTH = minWidth; MAX_WIDTH = maxWidth;
        MIN_HEIGHT = minHeight; MAX_HEIGHT = maxHeight;
    }
}

Then you can use anytime as is just like this :

System.out.printf("LEFT=%d, ", ScreenArea.LEFT);
System.out.printf("RIGHT=%d%n", ScreenArea.RIGHT);
System.out.printf("TOP=%d, ", ScreenArea.TOP);
System.out.printf("BOTTOM=%d%n", ScreenArea.BOTTOM);
System.out.printf("MIN_WIDTH=%d, ", ScreenArea.MIN_WIDTH);
System.out.printf("MAX_WIDTH=%d%n", ScreenArea.MAX_WIDTH);
System.out.printf("MIN_HEIGHT=%d, ", ScreenArea.MIN_HEIGHT);
System.out.printf("MAX_HEIGHT=%d%n", ScreenArea.MAX_HEIGHT);
System.out.printf("SCREEN_AREA=%s%n", ScreenArea.RECTANGLE);

Which on my dual monitor setup it prints :

LEFT=0, RIGHT=3840
TOP=0, BOTTOM=1080
MIN_WIDTH=1920, MAX_WIDTH=1920
MIN_HEIGHT=1080, MAX_HEIGHT=1080
SCREEN_AREA=java.awt.Rectangle[x=0,y=0,width=3840,height=1080]
Lorenzo
  • 591
  • 7
  • 18
1
int resolution =Toolkit.getDefaultToolkit().getScreenResolution();

System.out.println(resolution);
Eric Warriner
  • 1,163
  • 10
  • 15
0
int screenResolution = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println(""+screenResolution);
Draken
  • 3,134
  • 13
  • 34
  • 54
  • Welcome to Stack Overflow! While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – kayess Dec 20 '16 at 14:43