Java Swing GUI

How to Set JFrame in Center of the Screen

In this tutorial, we are going to see how to set JFrame in the center of the screen in Java Swing. To change the position of JFrame on the screen, JFrame provides the method JFrame.setlocation(int x, int y), you need two parameters ‘x’ represents the position of the x axis and ‘y’ represents the position of the y axis. The upper left corner of your screen is (0,0). If you give NULL as parameter to JFrame.setLocationRelativeTo() method, it will set the JFrame in the center of the screen. See the example below.
 

Java Program to Set JFrame in Center of the Screen:
import javax.swing.JFrame;

public class Main 
{  
  public static void main(String[] args)
  {
	JFrame frame = new JFrame();
	frame.setSize(300, 300);  
	
	// set JFrame in center of the screen
	frame.setLocationRelativeTo(null); 
	
	frame.setVisible(true);
  }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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