运行时为什么框架不在此GUI程序中居中?

Use*_*ser 1 java user-interface swing

package guilabq;

import java.awt.*;
import javax.swing.*;

public class GUI {

    JFrame f=new JFrame();//Creating a frame
    JTextArea area=new JTextArea();
    JScrollPane scroll=new JScrollPane(area);
    JRadioButton b1=new JRadioButton("Wrap");
    JRadioButton b2=new JRadioButton("Wrap Words");
    JRadioButton b3=new JRadioButton("Wrap Characters");
    ButtonGroup grp=new ButtonGroup();
    JPanel p1=new JPanel();//Creating a panel

    GUI() {
        grp.add(b1);
        grp.add(b2);//Grouping the buttons
        grp.add(b3);

        p1.add(b1);
        p1.add(b2);
        p1.add(b3);
        p1.setLayout(new GridLayout(1,3));
        p1.setBorder(new TitledBorder("Wrap Options"));

        f.add(scroll,BorderLayout.CENTER);
        f.add(p1,BorderLayout.SOUTH);

        f.setLocationRelativeTo(null);//Here I have tried to center the frame                                                
        f.pack();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(400, 300);
        f.setVisible(true);
    }

    public static void main(String[]args) {
        new GUI();
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我试图通过使用该方法使框架居中,setLocationRelativeTo(null);但我不明白为什么它没有出现在中心.它从中心出现在右下方和右侧.

小智 5

移动

f.setLocationRelativeTo(null);//Here I have tried to center the frame
Run Code Online (Sandbox Code Playgroud)

f.setSize(400, 300);
Run Code Online (Sandbox Code Playgroud)

像这样:

    f.pack();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(400, 300);
    /** Moved here **/
    f.setLocationRelativeTo(null);//Here I have tried to center the frame
    f.setVisible(true);
Run Code Online (Sandbox Code Playgroud)