Centers the window over the given component. - Java Swing

Java examples for Swing:JComponent

Description

Centers the window over the given component.

Demo Code


//package com.java2s;
import java.awt.Component;

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

public class Main {
    /**/*from  w w  w .ja  v a 2s . com*/
     * Centers the <code>window</code> over the given <code>component</code>.
     * The <code>window</code> might not be exactly centered over the
     * <code>component</code> if the <code>window</code> would not fit on the
     * screen if set to the calculated position.
     * <p>
     * The window instance must be visible, otherwise the location won't be set.
     * 
     * @param window
     *            The <code>window</code> to be positioned.
     * @param component
     *            The <code>component</code>, the <code>window</code> should be
     *            centered over.
     */
    public static void setLocationCenteredToComponent(Window window,
            Component component) {
        if (component != null && component.isVisible()) {
            Point componentLocation = component.getLocationOnScreen();
            Point componentCenter = new Point(componentLocation.x
                    + component.getWidth() / 2, componentLocation.y
                    + component.getHeight() / 2);

            window.setLocation(componentCenter.x - window.getWidth() / 2,
                    componentCenter.y - window.getHeight() / 2);
        }
    }
}

Related Tutorials