devxlogo

Center Your Frames/Dialogs

Center Your Frames/Dialogs

You can find many tips on how to center a window within the screen, but howabout centering a window in its parent container? The following code showsyou how to do that. Say you have a JFrame (or Frame), and you launch a JDialog (or Dialog) likethis:

 JDialog jd = new JDialog(this); //you have to pass the this pointer of Frame to establish//parent-child (or owner-owned) relationshipjd.setVisible(true);

In the code for jd you can have the following to center the dialog withrespect to its ownere frame:

 public void centerInParent () {    int x;    int y;    Container parent = this.getParent();    Point topLeft = parent.getLocationOnScreen();    Dimension parentSize = parent.getSize();    Dimension ownSize = this.getSize();    if (parentSize.width < ownSize.width)         {x = ((parentSize.width - ownSize.width)/2) +
topLeft.x;} else {x = topLeft.x;} if (parentSize.height < ownSize.height) {y = ((parentSize.height - ownSize.height)/2) +
topLeft.y;} else {y = topLeft.y;} this.setLocation (x, y); this.requestFocus();}

For the sake of completeness, the following code centers a Dialog or Framewithin the screen:

 public void centerInScreen() {    Dimension dim = this.getToolkit().getScreenSize();    Rectangle bounds = this.getBounds();    this.setLocation((dim.width - bounds.width) / 2, 
(dim.height -bounds.height) / 2); this.requestFocus();}
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist