Java examples for Swing:JComponent
Centers a component on its parent.
//package com.java2s; import java.awt.Component; import java.awt.Container; import java.awt.Rectangle; public class Main { /**//from w w w .j av a 2 s. c o m * Centers a component on its parent. * * @param component */ public static void centerInParent(Component component) { Container parent = component.getParent(); if (parent != null) { Rectangle parentBounds = parent.getBounds(); Rectangle dialogBounds = new Rectangle( (int) (parentBounds.getMinX() + parentBounds.getWidth() / 2 - component.getWidth() / 2), (int) (parentBounds.getMinY() + parentBounds.getHeight() / 2 - component .getHeight() / 2), component.getWidth(), component.getHeight()); //dialog.setBounds( dialogBounds ); component.setLocation(dialogBounds.x, dialogBounds.y); } } }