How to set JFrame to appear centered, regardless of monitor resolution? How to set JFrame to appear centered, regardless of monitor resolution? java java

How to set JFrame to appear centered, regardless of monitor resolution?


Use setLocationRelativeTo(null)

This method has a special effect when you pass it a null. According to the Javadoc:

If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

This should be done after setting the size or calling pack(), but before setting it visible, like this:

frame.pack();frame.setLocationRelativeTo(null);frame.setVisible(true);


I always did it in this way:

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);

where this is the JFrame involved.


You can call JFrame.setLocationRelativeTo(null) to center the window. Make sure to put this before JFrame.setVisible(true)