How to Center a JFrame in the Screen

At the beginning of my apprenticeship, I asked myself the question: how do I put the window in the center of my screen? I used the method  setLocationRelativeTo  and pass the null.

Here is an example that shows this technique, the setLocationRelativeTo(null) method is called at the end of the constructor.

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

public class JFrame_center extends JFrame{

public static void main(String[] args) {

JFrame frame = new JFrame("JFrame center");
frame.pack();

//retrieve screen size
SizeScreen size = Toolkit.getDefaultToolkit().getScreenSize();
int height = screensize.height;
int width = sizeScreen.width;
//size is half the length and height
frame.setSize(width/2, height/2);

//here we center our window
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Output
center JFrame or java screen window

That's it! Our window is nicely aligned in the center of the screen. In this program the method has been called getScreenSize  of the class  java Toolkit  to retrieve the size of the screen from which the program is running. This method is very efficient because it returns the dimension according to the user's screen.

Reference
Create a JFrame GUI with SWING