Center a Dialog Box, Frame or Window in Java

Are you tired of the random location of the windows in your application? It is time to take control of your window's position. This Java tutorial looks at how to center a dialog box, frame, or window in Java.

Java 1.4 or newer
If you are using Java 1.4 or newer, you can use the simple method setLocationRelativeTo(null) on the dialog box, frame, or window to center it.

Java 1.3 or older
We can query the toolkit to determine the size of the screen. The getScreenSize() method will return a Dimension object which contains the width and height.

//Get the screen size
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
Once you have the screen width and height, you can simply subtract the window width and height from the screen width and height and divide it in half.
//Create a new JFrame
JFrame frame = new JFrame("Demo");
frame.setSize(400, 600);

//Calculate the frame location
int x = (screenSize.width - frame.getWidth()) / 2;
int y = (screenSize.height - frame.getHeight()) / 2;

//Set the new frame location
frame.setLocation(x, y);
In our example above, we centered a JFrame, but the same code will work for a dialog box or a window.

Let's extend our example to create a dialog box class that will automatically center itself. Our CenterDialogBox class will extend a JDialog and over-ride the setSize() method. The dialog box will center itself after the setSize() method has been called.
//Create a new JFrame
public class CenterDialogBox extends JDialog
{
public void setSize(int width, int height)
{
super.setSize(width, height);

//Get the screen size
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();

//Calculate the frame location
int x = (screenSize.width - getWidth()) / 2;
int y = (screenSize.height - getHeight()) / 2;

//Set the new frame location
setLocation(x, y);
}

public void setSize(Dimension size)
{
setSize(size.width, size.height);
}
}

You can also use this to create your own class that can create a self-centering JWindow or JFrame.


11 comments:

Juan R. said...

Very useful post.
Quick and easy.

Anonymous said...

Awesome. Thank you for sharing. You just saved my half an hour of digging.

DeEpCoder said...

Thank you guys!
Saved hell of a lot of time!
Hope you can help me again sometime

Anonymous said...

maybe i'm noob to java..but why my error is (cannot find symbol class Dimension) what should i do?

Kevin said...

Dimension is in the java.awt package.

Anonymous said...

Thank you very much for this post, it's very useful.

Anonymous said...

Excellent advice! Good Work

Anonymous said...

Thanks!
Hope I can help you 1 day too...

Anonymous said...

Great, thanks!

Anonymous said...

wohow! great!
thanks! :)

~akshay!

Anonymous said...

thanks... :)

Post a Comment