Centering a Frame on the Screen

import java.awt.*;

public class CenteredFrameTester {

  public static void main(String[] args) {
        
    Frame myFrame = new Frame("My Frame");
    myFrame.setSize(250, 250);
    
    Toolkit kit = myFrame.getToolkit();
    Dimension screenSize = kit.getScreenSize();
    int screenWidth = screenSize.width;
    int screenHeight = screenSize.height;
    Dimension windowSize = myFrame.getSize();
    int windowWidth = windowSize.width;
    int windowHeight = windowSize.height;
    
    int upperLeftX = (screenWidth - windowWidth)/2;
    int upperLeftY = (screenHeight - windowHeight)/2;
    
    myFrame.setLocation(upperLeftX, upperLeftY);
    myFrame.add("Center", new TextArea(10, 40));
    myFrame.show();
    
  }
  
}

In practice I would combine several of these steps.


Previous | Next | Top
Last Modified November 15, 1999
Copyright 1997-1999 Elliotte Rusty Harold
elharo@metalab.unc.edu