Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java
Expertise: Intermediate
Sep 29, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Center Your Frames/Dialogs

You can find many tips on how to center a window within the screen, but how about centering a window in its parent container? The following code shows you how to do that. Say you have a JFrame (or Frame), and you launch a JDialog (or Dialog) like this:
JDialog jd = new JDialog(this); 
//you have to pass the this pointer of Frame to establish
//parent-child (or owner-owned) relationship
In the code for jd you can have the following to center the dialog with respect 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 Frame within 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(); }
Behrouz Fallahi
Comment and Contribute






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



Thanks for your registration, follow us on our social networks to keep up-to-date