Center Component on screen - Java java.awt

Java examples for java.awt:Component

Description

Center Component on screen

Demo Code


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

public class Main {
    /**//from w w w  .  j  a  va 2s . c  om
     * Center on screen
     *
     * @param thisComponent
     *            component to center
     */
    static public void center(final Component thisComponent) {
        final Dimension thisScreenSize = Toolkit.getDefaultToolkit()
                .getScreenSize();
        final Dimension thisComponentSize = thisComponent.getSize();
        if (thisComponentSize.height > thisScreenSize.height) {
            thisComponentSize.height = thisScreenSize.height;
        }
        if (thisComponentSize.width > thisScreenSize.width) {
            thisComponentSize.width = thisScreenSize.width;
        }
        thisComponent.setLocation(
                (thisScreenSize.width - thisComponentSize.width) / 2,
                (thisScreenSize.height - thisComponentSize.height) / 2);
    }
}

Related Tutorials