Centering Dialogs

Where does a dialog go when you show() it?

Unfortunately, the default location of a displayed dialog is relative to the position it was placed in the Visual Composition Editor.

What the hell does that mean???

In a nutshell, if the dialog is 300 pixels to the right and 200 pixels down from the upper-left corner of the design area, it will appear at absolute screen location 300, 200.

This isn't good...

This can cause several problems.  So how to deal with it?  Let's define a subclass of Dialog that provides a method that can center it with regard to it parent Frame.

When you create a dialog, you must pass it the parent Frame.  This Frame can be obtained via the Dialog's getParent() method.  We'll define a subclass of Dialog called CenterableDialog that will look at the parent Frame and determine where to place the dialog.  We must be careful and watch out for the screen edges too!

The CenterableDialog class...

Here's the code.  Once you define this class, all you have to do is:

import java.awt.Dialog;

import java.awt.Dimension;

import java.awt.Point;

import java.awt.Frame;

public class CenterableDialog extends Dialog {

  public CenterableDialog(Frame parent) {



  public CenterableDialog(Frame parent,

                          String title) {

    super(parent, title);


  public CenterableDialog(Frame parent,

                          String title,

                          boolean modal) {

    super(parent, title, modal);


  public CenterableDialog(Frame parent,

                          boolean modal) {

    super(parent, modal);


  public void showCentered() {

    Frame parent = (Frame)getParent();

    Dimension dim = parent.getSize();

    Point     loc = parent.getLocationOnScreen();

    Dimension size = getSize();

    loc.x += (dim.width  - size.width)/2;

    loc.y += (dim.height - size.height)/2;

    if (loc.x < 0) loc.x = 0;

    if (loc.y < 0) loc.y = 0;

    Dimension screen = getToolkit().getScreenSize();

    if (size.width  > screen.width)

      size.width  = screen.width;

    if (size.height > screen.height)

      size.height = screen.height;

    if (loc.x + size.width > screen.width)

      loc.x = screen.width - size.width;

    if (loc.y + size.height > screen.height)

      loc.y = screen.height - size.height;

    setBounds(loc.x, loc.y, size.width, size.height);





What about FileDialog?

You can use the same subclass trick on FileDialog -- it would look exactly the same as the above, except for the name of the class.