Java Essential Tips: Display JFrame in Center of the Screen

Target Audience: Java Beginners, Java Swing Developers

What should you know already? Basics of Java Swing

The beginners of Java might query “How do I display JFrame in center of screen?” on Google quite frequently. JFrame is the top level container in Swing API to show your GUI application.

Commonly, there are 2 methods available for setting location to any subclass of Component. They are:

  • setLocation(int x, int y)
  • setLocationRelativeTo(Component parent)

The first method accepts 2 integer values as X and Y co-ordinates on the screen. So, if you use this method, your JFrame would appear at the specific location.

The second method needs a Component. It sets the location of your JFrame relative to this component. If the component is not showing or it is null, then JFrame would be placed in center of the screen.

Look at the following source code for centering JFrame on the screen:

import javax.swing.JFrame;
import javax.swing.JLabel;
public class DemoTopLevel {
    public DemoTopLevel() {
        JFrame frame=new JFrame("Demo");
        JLabel lbl=new JLabel("Hello World! Exploring Java Swing API!!!");
        frame.getContentPane().add(lbl);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    public static void main(String [] arguments){
        new DemoTopLevel();
    }
}

Note: The setLocationRelativeTo(null); code must be after calling pack() or setSize() method. Otherwise it would set the location first then changes its width and height, which is actually not visible at center of the screen.

Feel free to send comments. About Author

Similar Posts

Permanent link to this article: https://blog.openshell.in/2011/05/java-essential-tip-display-jframe-in-center-of-the-screen/

Leave a Reply

Your email address will not be published.