How do I center a JFrame?

Viewed 153

I know that another person already asked this question. The answer is supposedly frame.setLocationRelativeTo(null);, but when I try using this method, the JFrame ends up being on the bottom right corner of my screen. Why is this, and what else should I do to center my JFrame?

The first thing below is the code that I wrote (I was writing an Animalese translator by the way), and the second is a link to an image of what happens when I run the code.

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class AnimaleseTranslator {
    public static void main(String[] args) {        
        JFrame frame = new JFrame();        
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(220, 391, 220, 391));
        panel.setLayout(new GridLayout(0, 1));      
        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setTitle("Animalese Translator");
        frame.pack();
        frame.setVisible(true);     
    }
}

The JFrame is supposed to be in the center of the screen since I wrote the frame.setLocationRelativeTo(null); line, but instead it is in the bottom right corner of the screen.

1 Answers

You should call pack before setLocationRelativeTo.

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Related