Java tutorial
//package com.java2s; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; public class Main { public static void centerComponent(Component relativeTo, Component toCenter) { if (relativeTo == null) { Toolkit tk = Toolkit.getDefaultToolkit(); Dimension screenSize = tk.getScreenSize(); int screenHeight = screenSize.height; int screenWidth = screenSize.width; toCenter.setLocation((screenWidth / 2) - (toCenter.getSize().width / 2), (screenHeight / 2) - (toCenter.getSize().height / 2)); } else { Point loc = relativeTo.getLocationOnScreen(); Rectangle bounds = relativeTo.getBounds(); toCenter.setLocation((int) (loc.x + bounds.getWidth() / 2) - (toCenter.getWidth() / 2), (int) (loc.y + bounds.getHeight() / 2) - (toCenter.getHeight() / 2)); } } }