Java Window Center centerOnParent(final Window child, final boolean absolute)

Here you can find the source of centerOnParent(final Window child, final boolean absolute)

Description

Center on parent ( absolute true/false (exact center or 25% upper left) )

License

Open Source License

Parameter

Parameter Description
child a parameter
absolute a parameter

Declaration

public static void centerOnParent(final Window child, final boolean absolute) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.awt.Dimension;

import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Window;

import javax.swing.JDialog;
import javax.swing.JFrame;

public class Main {
    /**//  w  w  w . j a v  a 2 s .  c o  m
     *  Center on parent ( absolute true/false (exact center or 25% upper left) )
     * @param child
     * @param absolute
     */
    public static void centerOnParent(final Window child, final boolean absolute) {
        child.pack();
        boolean useChildsOwner = child.getOwner() != null
                ? ((child.getOwner() instanceof JFrame) || (child.getOwner() instanceof JDialog))
                : false;
        final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        final Dimension parentSize = useChildsOwner ? child.getOwner().getSize() : screenSize;
        final Point parentLocationOnScreen = useChildsOwner ? child.getOwner().getLocationOnScreen()
                : new Point(0, 0);
        final Dimension childSize = child.getSize();
        childSize.width = Math.min(childSize.width, screenSize.width);
        childSize.height = Math.min(childSize.height, screenSize.height);
        child.setSize(childSize);
        int x;
        int y;
        if ((child.getOwner() != null) && child.getOwner().isShowing()) {
            x = (parentSize.width - childSize.width) / 2;
            y = (parentSize.height - childSize.height) / 2;
            x += parentLocationOnScreen.x;
            y += parentLocationOnScreen.y;
        } else {
            x = (screenSize.width - childSize.width) / 2;
            y = (screenSize.height - childSize.height) / 2;
        }
        if (!absolute) {
            x /= 2;
            y /= 2;
        }
        child.setLocation(x, y);
    }
}

Related

  1. centerPosition(Window window, Window w, int width, int height)
  2. centerWindow(Window w)
  3. packAndCenterWindow(Window dlg)
  4. packAndDisplayInCenterOfScreen(final Window f)