Java Screen Center setCenter(Component comp, Component parent)

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

Description

Center a component within a parental component.

License

Open Source License

Parameter

Parameter Description
comp the component to be centered.
parent center relative to what. <code>null</code> to center relative to screen.

Declaration

public static void setCenter(Component comp, Component parent) 

Method Source Code


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

Related

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