Thursday, 21 October 2021

Java: Find the screen resolution (width x height) in pixels

In this post, I am going to explain multiple ways to find the screen resolution programmatically.


 

Approach 1: Using Toolkit#getScreenSize method.

Toolkit#getScreenSize method return the size of the screen. In case of systems with multiple displayes, this method considers the dimensions of primary display.

 

ScreenResolutionDemo1.java

package com.sample.app.awtprograms;

import java.awt.Dimension;
import java.awt.Toolkit;

public class ScreenResolutionDemo1 {

	public static void main(String args[]) {
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		double width = screenSize.getWidth();
		double height = screenSize.getHeight();
		
		System.out.println("Screen width : " + width);
		System.out.println("Screen height : " + height);
	}

}

Output

Screen width : 1680.0
Screen height : 1050.0


Note

Even though ‘Toolkit.getScreenSize()’ method documentation says that it returns the screen size of the primary monitor on multi-monitor systems. But this is not working as expected on multi-monitor system. Refer this bug (https://bugs.java.com/bugdatabase/view_bug.do?bug_id=5100801) for more information.

 

If you also have this problem, use below snippet to find the dimensions of a primary display in a multi-monitor system.

 

ScreenResolutionDemo2.java

package com.sample.app.awtprograms;

import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;

public class ScreenResolutionDemo2 {
	public static void main(String args[]) {
		GraphicsDevice graphicDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();

		DisplayMode displayMode = graphicDevice.getDisplayMode();

		double width = displayMode.getWidth();
		double height = displayMode.getHeight();

		System.out.println("Screen width : " + width);
		System.out.println("Screen height : " + height);

	}

}


Output

Screen width : 1680.0
Screen height : 1050.0


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment