java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 MainForm.

package com.javacoderanch.examples.javax.swing;

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

public class MainForm 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();

                MainForm mainForm = new MainForm();
                mainForm.setDefaultCloseOperation(
                    JFrame.EXIT_ON_CLOSE);
                
                mainForm.setSize(250, 250);

                // Calculates the position where the MainForm
                // should be paced on the screen.
                mainForm.setLocation((screenSize.width - 
                    mainForm.getWidth()) / 2, 
                    (screenSize.height - 
                    mainForm.getHeight()) / 2);

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