Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata