What's the easiest way to centre a java.awt.Window
, such as a JFrame
or a JDialog
?
views:
1176answers:
3
+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
2008-09-28 00:49:52
You learn something new every day.
Joe Skora
2008-09-28 00:58:28
+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
2008-09-28 01:33:16
+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
2008-09-30 03:39:07