Recipe 14.14 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 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. Be aware that some platforms (Mac, Unix) make it pretty easy for the power user to have multiple monitors active, so you don't always want to do this.

Discussion

The code for this is pretty simple. The part that might take a while to figure out is the Dimension of the screen. Two methods can help: getScreenSize( ) in the Toolkit class and the static method getDefaultToolkit( ). (The Toolkit class relates to the underlying windowing toolkit; it has several subclasses, including two different ones for X Windows on Unix (Motif and non-Motif), 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 . 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, newY);     }     /** Center a Window, Frame, JFrame, Dialog, etc.,       * but do it the American Spelling Way :-)      */     public static void center(Window w) {         UtilGUI.centre(w);     } }

To use it after the relevant import, you can simply say, for example:

myFrame.pack( ); UtilGUI.centre(myFrame); myFrame.setVisible(true);



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net