How do I make a centered JFrame?

If you have a JFrame in your Java Swing application and want to center its position on the screen you can use the following formula.

package org.kodejava.example.swing;

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

public class CenteredJFrame extends JFrame {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            // Get the size of the 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.setVisible(true);
        });
    }
}

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply