How to center a JFrame on screen

I'm often asked, “How do I center a JFrame on screen?”, or, “Is there a method to center a JFrame?”

I always center my initial JFrame on screen using the setLocationRelativeTo method, and pass it a null reference, like this:

frame.setLocationRelativeTo(null);

As the Javadoc for the setLocationRelativeTo method states:

Sets the location of the window relative to the specified component. If the component is not currently showing, or c (the Component) is null, the window is centered on the screen.

You’d think a method named setCentered(boolean) would be a little more obvious, but hey, that’s how it works.

JFrame centering: Example source code

Here’s some Java source code that demonstrates this technique. You’ll see the frame.setLocationRelativeTo(null) method call near the end of this constructor method:

public ImageRotatorMain()
{
  // create a new jframe, and pack it
  frame = new MainFrame(this);
  frame.pack();

  // make the frame half the height and width
  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
  int height = screenSize.height;
  int width = screenSize.width;
  frame.setSize(width/2, height/2);

  // here's the part where i center the jframe on screen
  frame.setLocationRelativeTo(null);
  
  frame.setVisible(true);
}

If you try this in your own Java/Swing programs, I think you'll see that it centers a JFrame very nicely.

A complete Java “center JFrame on screen” program

Sometimes it helps to see the source code for a complete Java program to understand something, and to that end, here is a complete Java class that demonstrates this “JFrame centering” technique:

package com.devdaily.swing;

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;

public class CenterJFrameOnScreen
{
  public static void main(String[] args)
  {
    new CenterJFrameOnScreen();
  }
  
  public CenterJFrameOnScreen()
  {
    // create a new jframe, and pack it
    JFrame frame = new JFrame();
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // make the frame half the height and width
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int height = screenSize.height;
    int width = screenSize.width;
    frame.setSize(width/2, height/2);

    // center the jframe on screen
    frame.setLocationRelativeTo(null);
    
    frame.setVisible(true);
  }
}

NOTE: I should do some of that Swing stuff with SwingUtilities.invokeLater (i.e., on the event dispatching thread, or EDT), but I'm trying to keep this example simple. Click the URL that follows for an example of how to properly call SwingUtilities.invokeLater.

As mentioned, I think you'll see that this program creates a Java JFrame that is centered on your screen.