How to center a Window in Java?

Viewed 223925

What's the easiest way to centre a java.awt.Window, such as a JFrame or a JDialog?

19 Answers

From this link

If you are using Java 1.4 or newer, you can use the simple method setLocationRelativeTo(null) on the dialog box, frame, or window to center it.

This should work in all versions of Java

public static void centreWindow(Window frame) {
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
    frame.setLocation(x, y);
}

Note that both the setLocationRelativeTo(null) and Tookit.getDefaultToolkit().getScreenSize() techniques work only for the primary monitor. If you are in a multi-monitor environment, you may need to get information about the specific monitor the window is on before doing this kind of calculation.

Sometimes important, sometimes not...

See GraphicsEnvironment javadocs for more info on how to get this.

Example: Inside myWindow() on line 3 is the code you need to set the window in the center of the screen.

JFrame window;

public myWindow() {

    window = new JFrame();
    window.setSize(1200,800);
    window.setLocationRelativeTo(null); // this line set the window in the center of thr screen
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setBackground(Color.BLACK);
    window.setLayout(null); // disable the default layout to use custom one.
    window.setVisible(true); // to show the window on the screen.
}

The order of the calls is important:

first -

pack();

second -

setLocationRelativeTo(null);

In addition to Donal's answer, I would like to add a small calculation that makes sure that the Java window is perfectly at the center of the window. Not just the "TOP LEFT" of the window is at the center of the window.

public static void centreWindow(JFrame frame, int width, int height) {
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);

        // calculate perfect center
        int perf_x = (int) x - width/2;
        int perf_y = (int) y - height/2;

        frame.setLocation(perf_x, perf_y);
    }

If you want a simple answer for Java NetBeans:

Right click on the JFrame, go to properties, then go to code and select generate center option.

Look image for reference: [1]: https://i.stack.imgur.com/RFXbL.png

If you want to push center of your app window, you can do solved to follow.

int x = (Toolkit.getDefaultToolkit().getScreenSize().width) - getSize().width) / 2;
int y = (Toolkit.getDefaultToolkit().getScreenSize().height) - getSize().height) / 2;
setLocation(x,y);

getSize() function is app frame size... getScreenSize() is your pc screen size.

Related