How to Center a JFrame Window in Java

Center a JFrame Window in Java

In this tutorial, I am writing simple program about, How to Center a JFrame Window in Java. The example Java Swing Program has been tested, and screen shot of Output is shared in the same post.

CenterWindow.java

package com.dineshkrish.swing;

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class CenterWindow extends JFrame {

	public CenterWindow(String title, boolean visibility) {
	
		super.setTitle(title);
		super.setSize(600, 400);
		super.setVisible(true);
		
		Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
	    int x = (int) ((screen.getWidth() - this.getWidth()) / 2);
	    int y = (int) ((screen.getHeight() - this.getHeight()) / 2);
	    
	    this.setLocation(x, y);
	}
	
	public static void main(String[] args) {

		// Defining Object
		CenterWindow window = new CenterWindow("My Application", true);
	}
}

Output

Center a JFrame Window in Java

References

1. How to center a Window in Java
2. Java API Documentation

Hello everyone, I am a Founder of dineshkrish.com.