Wednesday, March 9, 2011

How to center the form(JFrame) in the screen in java

This example shows how to center a form in your screen
 import java.awt.Dimension;
 import java.awt.Toolkit;
 import javax.swing.JFrame;


 public static void main(String[] args){
    JFrame myForm = new JFrame("Centered Form");
    myForm.setSize(250, 200);
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenSize = toolkit.getScreenSize();
    //Following three lines make the form centered
    int x = (screenSize.width - myForm.getWidth())/2;
    int y = (screenSize.height - myForm.getHeight())/2;
    myForm.setLocation(x, y);
    myForm.setVisible(true);
}

No comments:

Post a Comment