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.

Example


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();
		windowAtCenter.setVisible(true);
	}
	
	public WindowAtCenter() {
		setSize(300, 250);
		setTitle("Window at center");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		Toolkit toolKit = getToolkit();
		Dimension size = toolKit.getScreenSize();
		setLocation(size.width/2 - getWidth()/2, size.height/2 - getHeight()/2);
	}
}

Output:

Screenshot-2021-02-07-at-11-47-23-PM
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.



About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *