Here you can find the source of setCenter(Component comp)
Parameter | Description |
---|---|
comp | the component to be centered relative to the screen. It must already have its final size set. |
public static void setCenter(Component comp)
//package com.java2s; // Public License. See LICENSE.TXT for details. import java.awt.Component; import java.awt.Dimension; import java.awt.Point; public class Main { /**//from w w w . ja v a2 s. com * 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. * @see #setCenter(Component, Component) */ 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); } /** * 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); } }