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

While working with Java, I find it hard to position my main window in the center of the screen when I start the application.

Is there any way I can do that? It doesn't have to be vertically centered, horizontal alignment is the more important goal for me. But vertical alignment is also welcome.


Solution 1:

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);

Solution 2:

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.

Solution 3:

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

Solution 4:

Just click on form and go to JFrame properties, then Code tab and check Generate Center.

enter image description here

Solution 5:

As simple as this...

setSize(220, 400);
setLocationRelativeTo(null);  

or if you are using a frame then set the frame to

frame.setSize(220, 400);
frame.setLocationRelativeTo(null);  

For clarification, from the docs:

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