Java Swing display JFrame window at center of the screen

Hey guys in this post, we will discuss how to place the JFrame window at the center of the screen.

Read: Create Basic JFrame window and display it on the Screen

When we create the JFrame window, by default it is not centered. It will always pop up at the top left corner of the screen. Let’s look at the example of how we can center the JFrame on the screen.


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

import javax.swing.JFrame;

public class WindowAtCenter extends JFrame{
	public static void main(String[] args) {
		WindowAtCenter windowAtCenter = new WindowAtCenter();
	public WindowAtCenter() {
		setSize(300, 250);
		setTitle("Window at center");
		Toolkit toolKit = getToolkit();
		Dimension size = toolKit.getScreenSize();
		setLocation(size.width/2 - getWidth()/2, size.height/2 - getHeight()/2);


In order to center the JFrame window, first, we need to know the resolution of the screen. So AWT has provided an abstract class Toolkit. It has a method getScreenSize(), which will give the Dimension of the screen. Then we will calculate width and height to center the window. We will call setLocation() to place the window on the screen.

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply