Java tutorial
//package com.java2s; /* (C) 2007 Stefan Reich (jazz@drjava.de) This source file is part of Project Prophecy. For up-to-date information, see http://www.drjava.de/prophecy This source file 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, version 2.1. */ import java.awt.*; public class Main { public static void centerInOwner(Dialog dialog) { Container parent = dialog.getOwner(); if (parent != null && parent.isShowing()) centerInParent(dialog, dialog.getParent()); else center(dialog); } public static void centerInParent(Window window, Component myParent) { int x; int y; Point topLeft = myParent.getLocationOnScreen(); Dimension parentSize = myParent.getSize(); Dimension mySize = window.getSize(); if (parentSize.width > mySize.width) x = ((parentSize.width - mySize.width) / 2) + topLeft.x; else x = topLeft.x; if (parentSize.height > mySize.height) y = ((parentSize.height - mySize.height) / 2) + topLeft.y; else y = topLeft.y; window.setLocation(x, y); } public static void center(Window window) { Dimension screen = window.getToolkit().getScreenSize(); window.setLocation((screen.width - window.getWidth()) / 2, (screen.height - window.getHeight()) / 2); } }