Here you can find the source of setCenter(Component comp, Component parent)
Parameter | Description |
---|---|
comp | the component to be centered. |
parent | center relative to what. <code>null</code> to center relative to screen. |
public static void setCenter(Component comp, Component parent)
//package com.java2s; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; public class Main { /**/*from w w w . ja v a 2s . co m*/ * Center a component within a parental component. * @param comp the component to be centered. * @param parent center relative to what. <code>null</code> to center relative to screen. * @see #setCenter(Component) */ public static void setCenter(Component comp, Component parent) { if (parent == null) { setCenter(comp); return; } Dimension dlgSize = comp.getPreferredSize(); Dimension frmSize = parent.getSize(); Point loc = parent.getLocation(); if (dlgSize.width < frmSize.width && dlgSize.height < frmSize.height) comp.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); else setCenter(comp); } /** * Center a component on the screen. * @param comp the component to be centered relative to the screen. * It must already have its final size set. * @preconditions comp.getSize() as on screen. */ public static void setCenter(Component comp) { Dimension screenSize = comp.getToolkit().getScreenSize(); Dimension frameSize = comp.getSize(); if (frameSize.height > screenSize.height) frameSize.height = screenSize.height; if (frameSize.width > screenSize.width) frameSize.width = screenSize.width; comp.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2); } }