Here you can find the source of centerWindowInFrame(Component window, Window frame)
public static void centerWindowInFrame(Component window, Window frame)
//package com.java2s; //License from project: Apache License import java.awt.Component; import java.awt.Dimension; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import javax.swing.SwingUtilities; public class Main { public static void centerWindowInFrame(Component window, Window frame) { // Note FileDialog instances in jdk 1.4.1 have no size until FileDialog.show() // which blocks i.e., we can't center FileDialogs. Dimension dimCenter;/*w ww .ja v a2 s. co m*/ Point ptOffset; if (frame != null) { if ((!(frame instanceof Frame) || ((Frame) frame).getState() != Frame.ICONIFIED) && frame.isShowing()) { // Center in frame dimCenter = frame.getSize(); ptOffset = frame.getLocation(); } else { // Retry either containing window or screen centerWindowInFrame(window, null); return; } } else { Window owner = SwingUtilities.getWindowAncestor(window); if (owner != null && owner.isShowing() && (owner.getMinimumSize().height < owner.getHeight())) { // Retry with owner window as frame if ((!(owner instanceof Frame) || ((Frame) owner).getState() != Frame.ICONIFIED) && owner.isShowing()) { // Center in frame dimCenter = owner.getSize(); ptOffset = owner.getLocation(); window.setLocation(ptOffset.x + (dimCenter.width - window.getWidth()) / 2, ptOffset.y + (dimCenter.height - window.getHeight()) / 2); } return; } // Center in screen Rectangle screenRect = getPrimaryMonitorScreenRect(); dimCenter = new Dimension((int) screenRect.getWidth(), (int) screenRect.getHeight()); ptOffset = new Point((int) screenRect.getX(), (int) screenRect.getY()); } window.setLocation(ptOffset.x + (dimCenter.width - window.getWidth()) / 2, ptOffset.y + (dimCenter.height - window.getHeight()) / 2); } public static Rectangle getPrimaryMonitorScreenRect() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gds = ge.getScreenDevices(); return gds[0].getConfigurations()[0].getBounds(); } }