运行时,为什么该GUI程序中的框架没有居中?

时间:2015-05-24 06:37:00

标签: java swing user-interface

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();
    }
}

在这里,我尝试使用setLocationRelativeTo(null);方法使框架居中,但我不明白为什么它没有出现在中心。它从中心出现在右下方。

1 个答案:

答案 0 :(得分:5)

移动

f.setLocationRelativeTo(null);//Here I have tried to center the frame

之后

f.setSize(400, 300);
像这样:

    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);