O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Centering a Main Window

Problem

You want your main window to be centered on the screen.

Solution

First, be aware that some users on some platforms would rather that you didn’t do this, as they have existing “placement” schemes. However, at least on MS-Windows, this technique is useful.

Subtract the width and height of the window from the width and height of the screen, divide by two, and go there.

Discussion

The code for this is pretty simple. The part that might take a while to figure out is the Dimension of the screen. There is a method getScreenSize( ) in the Toolkit class, and a static method getDefaultToolkit( ). (The Toolkit class relates to the underlying windowing toolkit; there are several subclasses of it, one for X Windows on Unix, another for Macintosh, etc.) Put these together and you have the Dimension you need.

Centering a Window is such a common need that I have packaged it in its own little class UtilGUI , just as I did for the WindowCloser class in Recipe 13.6. Here is the complete source for UtilGUI, which I’ll use without comment from now on:

package com.darwinsys.util; import java.awt.*; /** Utilities for GUI work. */ public class UtilGUI { /** Centre a Window, Frame, JFrame, Dialog, etc. */ public static void centre(Window w) { // After packing a Frame or Dialog, centre it on the screen. Dimension us = w.getSize( ), them = Toolkit.getDefaultToolkit().getScreenSize( ); int newX = (them.width - us.width) / 2; int newY = (them.height- us.height)/ 2; w.setLocation(newX, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required