How to display a JFrame to the center of a screen in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A JFrame is a subclass of Frame class and the components added to a frame are referred to as its contents, these are managed by the contentPane. We can add the components to a JFrame to use its contentPane instead. A JFrame is like a Window with border, title, and buttons. We can implement most of the java swing applications using JFrame.

By default, a JFrame can be displayed at the top-left position of a screen. We can display the center position of JFrame using the setLocationRelativeTo() method of Window class.


public void setLocationRelativeTo(Component c)


import javax.swing.*;
import java.awt.*;
public class JFrameCenterPositionTest extends JFrame {
   public JFrameCenterPositionTest() {
      setTitle("JFrameCenter Position");
      add(new JLabel("JFrame set to center of the screen", SwingConstants.CENTER),                BorderLayout.CENTER);
      setSize(400, 300);
      setLocationRelativeTo(null); // this method display the JFrame to center position of a screen
   public static void main (String[] args) {
      new JFrameCenterPositionTest();


Published on 11-Sep-2019 17:11:40