tags:

views:

1176

answers:

3

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

+12  A: 

From this blog:

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.

Andrew Swan
You learn something new every day.
Joe Skora
+3  A: 

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);
}
Don
+4  A: 

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.

Kevin Day
This helped me immensely! Thanks!
Joshua McKinnon