This method returns the point at which the incoming dialog will be perfectly centered on screen. - Java Swing

Java examples for Swing:JDialog

Description

This method returns the point at which the incoming dialog will be perfectly centered on screen.

Demo Code


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

public class Main {
    /**/*from   w  ww . j av a  2 s  .c o  m*/
     * This method returns the point at which the incoming dialog will be
     * perfectly centered on screen.
     * @param windowToCenter The window to center. Make sure thesize has been set (pack or validate first).
     * @return The point to set on the dialog using setLocation().
     */
    public static Point getCenteredWindowPoint(
            java.awt.Window windowToCenter) {
        //Center the Dialog
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = windowToCenter.getSize();
        if (frameSize.height > screenSize.height) {
            frameSize.height = screenSize.height;
        }
        if (frameSize.width > screenSize.width) {
            frameSize.width = screenSize.width;
        }
        Point centerCoord = new Point(
                (screenSize.width - frameSize.width) / 2,
                (screenSize.height - frameSize.height) / 2);
        return centerCoord;
    }
}

Related Tutorials