Java tutorial
//package com.java2s; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.Toolkit; public class Main { /** * Position the given component at the center of the given parent component or physical screen. * * @param c the component to be positioned * @param parent the component whose center will match the center of the given component. * If null, the given component will match the screen center. * */ public static void position(Component c, Component parent) { Dimension d = c.getPreferredSize(); if (parent == null) { Dimension s = Toolkit.getDefaultToolkit().getScreenSize(); c.setLocation(s.width / 2 - d.width / 2, s.height / 2 - d.height / 2); } else { Point p = parent.getLocationOnScreen(); int pw = parent.getWidth(); int ph = parent.getHeight(); c.setLocation(p.x + pw / 2 - d.width / 2, p.y + ph / 2 - d.height / 2); } } }