Java JFrame: How to create, center, and display a JFrame

Java JFrame FAQ: How do I properly create and display a JFrame? While you're at it, how do I center a JFrame?

In this Java tutorial I'll demonstrate how to create and display a JFrame Other than the comments in the source code, I'm going to keep the code as simple as possible, so I can demonstrate how this works.

Here's the complete source code for a Java class named SimpleJFrameDemo, that demonstrates how to construct and display a Java frame (a JFrame):

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

 * A sample class that demonstrates how to create and display a JFrame.
public class SimpleJFrameDemo
  public static void main(String[] args)
    SwingUtilities.invokeLater(new Runnable()
      public void run()
        // create a jframe, giving it an initial title
        JFrame frame = new JFrame("Simple JFrame Demo");
        // set the jframe size. in a more complicated application you will
        // probably call frame.pack() before displaying it.
        frame.setSize(new Dimension(300,200));
        // center the frame
        // set this so your application can easily be stopped/killed
        // display the frame


If you don't count all the import statements and boilerplate code, you can see that you can create and display a JFrame in less than 10 lines of code.

There are plenty of lines of comment in the source code, so I'll just add a few additional comments here:

  1. Execution starts in the main method of my SimpleJFrameDemo Java class.
  2. I use the SwingUtilities invokeLater method as a wrapper around most of my JFrame code. Unfortunately this is the most complicated line of code, and it comes first, but in general you use this technique to make sure you execute Swing code like this on the Event Dispatch Thread, or EDT. As I'll try to show in many examples on this blog, you only want to modify Swing (GUI) elements from the EDT (otherwise bad things will happen).
  3. The frame.setLocationRelativeTo(null) is a slightly-special way of centering the JFrame on screen. It's actually discussed in the JFrame Javadoc, but when you first start working with Swing and JFrame's this isn't obvious.
  4. The frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) method sets up your application so that when the user presses the close button on the window they see, your entire application will shut down. This technique is fine for simple applications like this, but with more complicated applications you'll want to control that shutdown process more carefully.

I hope this source code makes sense. I usually find it's easier to learn a new programming language when I can see complete examples, so I'm trying to share more examples like this throughout my blog.