Here you can find the source of centerWindow(Window w)
Parameter | Description |
---|---|
w | The window to center. |
public static final void centerWindow(Window w)
//package com.java2s; /*L/*from w w w.j ava 2s . c o m*/ * Copyright Georgetown University, Washington University. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cab2b/LICENSE.txt for details. */ import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.Window; import javax.swing.SwingUtilities; public class Main { /** Center a window on the screen. * @param w The window to center. */ public static final void centerWindow(Window w) { Dimension screenSize = w.getToolkit().getScreenSize(); Dimension windowSize = w.getSize(); int x = (screenSize.width - windowSize.width) / 2; int y = (screenSize.height - windowSize.height) / 2; w.setLocation(x, y); } /** Center a window within the bounds of another window. * * @param w The window to center. * @param parent The window to center within. */ public static final void centerWindow(Window parent, Window w) { Dimension windowSize = w.getSize(); Dimension parentSize = parent.getSize(); Point parentLocation = parent.getLocationOnScreen(); int x = ((parentSize.width - windowSize.width) / 2) + parentLocation.x; int y = ((parentSize.height - windowSize.height) / 2) + parentLocation.y; // If placing the window at (x,y) would make part if it off-screen, // then center it in the middle of the screen instead. Dimension screenSize = w.getToolkit().getScreenSize(); if (((x + windowSize.width) > screenSize.width) || (x < 0) || ((y + windowSize.height) > screenSize.height) || (y < 0)) { centerWindow(w); } else { w.setLocation(x, y); } } /** Center a window within the bounds of a component's parent window. * * @param w The window to center. * @param c The component within whose parent window this window should be * centered. If a window cannot be found in the component hierarchy above * <code>c</code>, the window is centered on the screen. */ public static final void centerWindow(Component c, Window w) { Window pw = SwingUtilities.windowForComponent(c); if (pw == null) { centerWindow(w); } else { centerWindow(pw, w); } } }