How to Center a Window on Screen

The customers’ computer has various resolution, it’s really hard to calculate location of frame to center a on screen. here is a piece of code to share to you. On a multimonitor system the window is centered on the same screen as the owner. If the window doesn’t have an owner it is centered on the primary screen.

/**
* Center window on screen.
* <p/>
* This method takes the screen insets (e.g. the Windows Taskbar) into
* account.
* <p/>
* On a multimonitor system the window is centered on the same screen
* as the owner. If the window doesn't have an owner it is centered on
* the primary screen.
*
* @param window      Window to center on screen.
* @param defaultSize Is used as size of the window. If set
*                    to null the result of getSize() is used.
* @throws NullPointerException if <code>window</code> is null.
* @since JMDK 3.0
*/
public static void centerOnScreen(Window window, Dimension defaultSize) {
   GraphicsConfiguration gc = window.getGraphicsConfiguration();
   Toolkit toolkit = window.getToolkit();
   Rectangle screenBounds = getScreenBounds(toolkit, gc);
   Dimension windowSize = (defaultSize != null) ? defaultSize : window.getSize();

   if (windowSize.width <= 0 && windowSize.height <= 0) {
      // Window has no preferred size. Use half of the screen size.
      windowSize = new Dimension(screenBounds.width / 2, screenBounds.height / 2);
   }

   if (windowSize.height > screenBounds.height) {
      windowSize.height = screenBounds.height;
   }
   if (windowSize.width > screenBounds.width) {
      windowSize.width = screenBounds.width;
   }

   int x = screenBounds.x + (screenBounds.width - windowSize.width) / 2;
   int y = screenBounds.y + (screenBounds.height - windowSize.height) / 2;

   window.setBounds(x, y, windowSize.width, windowSize.height);
}

Rate article
ASJAVA.COM
Add a comment

Your email address will not be published. Required fields are marked *

  1. Zrk

    There is a more convienent way to do this:

    When you want to center a widget which is inherited from Component, you can use the .setLocationRelativeTo() method with null as parameter.

    According to Javadoc, null value will have the same effect as your method 🙂

    Reply
    1. admin author

      Great, good to know that JDK library supports it.

      Reply