How do I center a dialog on top of a frame?

Scott Stanchfield

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:

  • Use CenterableDialog wherever you would normally use Dialog
  • Call showCentered() instead of show() to display the dialog. The reason we don't override show() itself is so we can still explicitly set the dialog's position and show() it non-centered.
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) {
    super(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);
    show();
  }
}

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.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact