How do I make a centered JFrame?

If you have a JFrame and you want to center the position in the screen you can use the following formula. Let’s say you have a class called CenteredJFrame.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class CenteredJFrame extends JFrame {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // Get the size of our screen
                Dimension screenSize =
                        Toolkit.getDefaultToolkit().getScreenSize();

                CenteredJFrame frame = new CenteredJFrame();
                frame.setTitle("Centered JFrame");
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

                frame.setSize(250, 250);

                // Calculates the position where the CenteredJFrame
                // should be paced on the screen.
                int x = (screenSize.width - frame.getWidth()) / 2;
                int y = (screenSize.height - frame.getHeight()) / 2;
                frame.setLocation(x, y);

                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}