Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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
jd.setVisible(true);
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.

 

 

Sitemap