Places the Component at the center of if parent. - Java Swing

Java examples for Swing:JComponent

Description

Places the Component at the center of if parent.

Demo Code

/*/*w  w w .  ja v a 2 s.com*/
 * Copyright 2007-2013
 * Licensed under GNU Lesser General Public License
 * 
 * This file is part of EpochX
 * 
 * EpochX is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * EpochX is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with EpochX. If not, see <http://www.gnu.org/licenses/>.
 * 
 * The latest version is available from: http://www.epochx.org
 */
//package com.java2s;

import java.awt.Component;

import java.awt.Dimension;
import java.awt.Rectangle;

public class Main {
    /**
     * Places the <code>Component</code> at the center of if parent.
     * 
     * @param comp the <code>Component</code> to centre.
     * @throws IllegalArgumentException if the component has no parent.
     */
    public static void centreRelativeToParent(Component comp)
            throws IllegalArgumentException {
        try {
            Rectangle r = comp.getParent().getBounds();
            Dimension d = comp.getSize();
            int x = (int) (r.getX() + (r.getWidth() - d.getWidth()) / 2);
            int y = (int) (r.getY() + (r.getHeight() - d.getHeight()) / 2);
            comp.setLocation(x, y);
        } catch (NullPointerException e) {
            throw new IllegalArgumentException(
                    "The component has no parent.");
        }
    }
}

Related Tutorials