How to center a Window in Java? How to center a Window in Java? java java

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.


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().