Search code examples
javascreen-resolution

How to get the screen DPI in java?


I am developing an app for which I need the screen DPI.. I checked a few forums and got a code snippet which goes as follows:

Dimension screen = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
System.out.println("screen width: "+screen.getWidth()); 
System.out.println("screen height: "+screen.getHeight()); 
int pixelPerInch=java.awt.Toolkit.getDefaultToolkit().getScreenResolution(); 
System.out.println("pixelPerInch: "+pixelPerInch); 

double height=screen.getHeight()/pixelPerInch; 
double width=screen.getWidth()/pixelPerInch; 
double x=Math.pow(height,2); 
double y=Math.pow(width,2); 

But whatever be the value of my screen resolution, the pixelPerInch value remains the same at 96. What is the problem with the code??

I got another swt code for the same thing which goes as follows:

  import org.eclipse.swt.graphics.Device;
  import org.eclipse.swt.widgets.Display;
  import org.eclipse.swt.widgets.Shell;

  public class MainClass {
  public void run() {
  Display display = new Display();
  Shell shell = new Shell(display);
  shell.setText("Display Device");
  createContents(shell);
  shell.pack();
  shell.open();
  while (!shell.isDisposed()) {
    if (!display.readAndDispatch()) {
      display.sleep();
    }
  }
  display.dispose();
}

private void createContents(Shell shell) {
  Device device = shell.getDisplay();

  System.out.println("getBounds(): "+ device.getBounds());
  System.out.println("getClientArea(): "+device.getClientArea());
  System.out.println("getDepth(): "+device.getDepth());
  System.out.println("getDPI(): "+device.getDPI());

  device.setWarnings(true);
  System.out.println("Warnings supported: "+device.getWarnings());
}

public static void main(String[] args) {
  new MainClass().run();
}

But again here also whatever be my screen resolution, the getDPI() returns the same value of 96.. What is going wrong?? Is my code wrong or am I interpreting it in a wrong way??


Solution

  • The problem is no one, not even the OS, knows the exact physical dimensions of the screen. You'd need to know that in order to calculate the PPI.

    There's a display setting in the control panel where the user can manually specify the PPI and by default it's set to 96.