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 examples.

The first way is to utilize java.awt.Toolkit class to get the screen size. The getScreenSize() method return a java.awt.Dimension from where we can get the widht and height of the screen. Having this values in hand we can calculate the top left position of our JFrame as shown in step 2 of the code below.

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() {
            @Override
            public void run() {
                // 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);
            }
        });
    }
}

The second example which is better and simpler is to use the setLocationRelativeTo(Component) method. According to the Javadoc of this method: If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

If you call the JFrame.pack() method. The method should be called before the setLocationRelativeTo() method.

So we can rewrite the code above like this:

package org.kodejava.example.swing;

import javax.swing.*;

public class CenteredJFrameSecond {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                CenteredJFrame frame = new CenteredJFrame();
                frame.setTitle("Centered JFrame");
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.setSize(250, 250);

                // Place the window in the center of the screen.
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply