java - 为什么这个 GUI 程序运行时框架没有居中?

标签 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); 方法使框架居中,但我不明白为什么它没有出现在中心。它出现在中心偏右下方。

最佳答案

移动

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

关于java - 为什么这个 GUI 程序运行时框架没有居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30420778/

相关文章:

c# - 在 MonoTouch 中获取没有 UI 的 iOS 屏幕分辨率

java - 创建动态 JTrees(控制根节点可见性)

python - 通过远程连接运行带有 GUI 的程序

ios - 动态调整大小 "container"UIView

java - 使用 netbeans 使用 Restful Web 服务时,http ://xmlns. jcp.org/xml/ns/persistence":persistence-unit}' 是预期错误

java - 在继续之前检查 jtable 中的重复数据

java - 程序编译但在 Mac 上不显示 GUI

java - 在 Apache POI 中读取 10 MB 文件

java - 在 Spigot 1.12.2 中打印列表<Player>

java - 是否可以在同一 Activity 中执行单独的网络线程而无需等待?