Your Computer Science Resource

HOW-TO: Center a JFrame On The Screen

If you want to add a nice touch to your GUI application, have your JFrame automatically center on the user’s screen. Not only does this looks much better than having it start up in the default (0, 0) location, but it takes very little coding effort to make this happen. There are two methods for doing this, depending on which version of Java you are using. I will show you how to do it both ways, though most of you can follow the first method.

Using Java 1.4 or later

If you are using Java 1.4 or later, you can use just one method from the Window class to center your frame on the screen, regardless of the user’s screen resolution.

The Code

Assuming you are extending JFrame, you can add this to your initialization method:

this.setLocationRelativeTo( null );

If you are not extending JFrame but rather instantiating a new JFrame in your code, you can do something like this instead:

// Assuming `frame` is the name of your JFrame
frame.setLocationRelativeTo( null );

Setting the location relative to null automatically centers the frame on the screen. If you’re not using Java 1.4 or later, use the below method instead.

Prior to Java 1.4

Prior to Java 1.4, you will want to get the user’s screen resolution and then calculate where to place your JFrame on the screen using the below code:

The Code

Assuming you are extending JFrame in your GUI class file, add the following method to the source:

private void centerWindow() {

	Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
	this.setLocation( dim.width / 2 - this.getWidth() / 2, dim.height / 2 - this.getHeight() / 2 );

}

Then, upon initialization, you will need to call this method. For example:

public void initialize() {

	...

	this.centerWindow();

	...

}

If you are NOT extending JFrame in your class file (i.e. you are instantiating a new JFrame somewhere instead), then you need to change the this to the frame name, or a method that returns the frame reference. For example, if the method getJFrame() returns our JFrame, then we can do the following instead:

private void centerWindow() {

	Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
	getJFrame().setLocation( dim.width / 2 - getJFrame().getWidth() / 2, dim.height / 2 - getJFrame().getHeight() / 2 );

}

Again, upon initialization, you will need to call this method:

public void initialize() {

	...

	getJFrame().centerWindow();

	...

}

The latter part of the code really depends on how you designed the class.

Enjoy!

Tags: , ,

Leave a Reply