How to center a Window in Java?
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.
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.
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);
}
setLocationRelativeTo(null)
should be called after you either use setSize(x,y)
, or use pack()
.