Java Screen Center setCenter(Component comp)

Here you can find the source of setCenter(Component comp)

Description

Center a component on the screen.

License

Open Source License

Parameter

Parameter Description
comp the component to be centered relative to the screen. It must already have its final size set.

Declaration

public static void setCenter(Component comp) 

Method Source Code

//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);
    }
}

Related

  1. moveToCenter(Component componentToMove, Component componentToCenterOver)
  2. moveToScreenCenter(Window w)
  3. packAndCenter(Window wind)
  4. packAndCenter(Window window)
  5. screenCenter(Window window)
  6. setCenter(Component comp, Component parent)
  7. setCenter(Component component)
  8. setCenter(Component component, Component component1)
  9. setCenteredCoordSystem(Graphics2D g, Component comp, double unitx, double unity)