How to center JFrame on screen?

We many times need to center the JFrame on screen , to center the JFrame on screen we can use setLocationRelativeTo method by passing null as owner.
Following is the code to set the JFrame at center position , first we are creating the JFrame and then packing it and then calling setLocationRelativeTo( null ).



// create a new jframe, and pack it
JFrame frame = new JFrame("Center Frame");
frame.pack();

//Set the frame size
frame.setSize( 500,400);

// centering the JFrame on screen
frame.setLocationRelativeTo(null);

frame.setVisible(true);


Note: We need to call pack before we call setLocationRelativeTo method , if we dont do it then JFrame wont able to collect the size we specify.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment