Centers an AWT window on the screen. - Java Swing

Java examples for Swing:Screen

Description

Centers an AWT window on the screen.

Demo Code


//package com.java2s;

import java.awt.Dimension;

import java.awt.Rectangle;
import java.awt.Window;

public class Main {
    /**/*from  ww w  .j av  a  2  s  .co  m*/
     * Centers a window on the screen.
     *
     * @param window window to center
     */
    public static void centerScreen(Window window) {
        if (window == null) {
            throw new NullPointerException("window == null");
        }

        Dimension screenDimension = window.getToolkit().getScreenSize();
        Rectangle frameBounds = window.getBounds();

        window.setLocation((screenDimension.width - frameBounds.width) / 2,
                (screenDimension.height - frameBounds.height) / 2);
    }
}

Related Tutorials