Saturday, August 22, 2009

Have you ever wanted your Form(java.swing) to be displayed on the center of your screen?????

In java there's no straight forward property to get displayed your FORM on the center of the screen.

Here's a method to do so...

First you have to import two packages ....

import java.awt.Dimension;
import java.awt.Toolkit;

Next go to the design view of your form & click on the form. In the properties of the form see what's the prefferedSize is.
say, prefferedSize = [426,473]

here 426 is the width of your form, & 473 is the length of the form.

Next initiate following variables,

Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
//this will get screen dimensions
int X = (screen.width / 2) - (426 / 2); // Center horizontally.
int Y = (screen.height / 2) - (700/ 2); // Center vertically.

here 426 is the width of your form & 700 is a value which makes your form vertically centered.
But you can change this 700 according to the vertical position you want.

Next again go to the properties of your form & go to bounds.
There select Custom Code & enter the following line.

this.X,this.Y,426,473

here 426 is the width & 473 is the length of your form.

Then press ok & check again whether the code line you entered is there.

Now run your form & see.

3 comments:

Unknown said...

i use the fallowing method in the constructor to do the same. it works for JFReam
setLocationRelativeTo(null);

rclakmal said...

That method works for JDialogs also !!

Nirmal Fernando said...

Ya, guys true!!!
I realized that while I using Eclipse IDE.