GridBagLayout 中未显示的元素

Elements not showing in GridBagLayout

我正在使用 GridBagLayout 作为 JFrame 布局。无论我写什么,我的元素都没有显示。请不要给出使用 GridBagLayout 以外的任何东西的答案(对不起,如果听起来很粗鲁)

JPanel Panel;
    JButton insertButton = new JButton("Insert");
    GridBagConstraints gbc;

    public MainFrame() {

        this.setTitle("JAVA & MySQL");
        this.setVisible(true);
        this.setBounds(500, 100, 600, 600);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        Panel = new JPanel(new GridBagLayout());
        Panel.setOpaque(true);
        Panel.setBackground(Color.BLUE);
        gbc = new GridBagConstraints();

        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.insets = new Insets(0, 10, 0, 0);
        gbc.fill = GridBagConstraints.BOTH;

        Panel.add(insertButton, gbc);




    }

您的代码不清楚在哪里(这段代码在您的框架内class)并且您选择的名称很糟糕。按照约定,字段名称应以小写字母开头(以区别于 class 名称)。

看来您从未将面板添加到框架中,而且您也从未 pack() 框架。

像这样修改代码:

public MainFrame() {
    this.setTitle("JAVA & MySQL");
    // setting visible should come last!
    //this.setVisible(true);
    this.setBounds(500, 100, 600, 600);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    Panel = new JPanel(new GridBagLayout());
    Panel.setOpaque(true);
    Panel.setBackground(Color.BLUE);
    gbc = new GridBagConstraints();

    gbc.weightx = 1;
    gbc.weighty = 1;
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.insets = new Insets(0, 10, 0, 0);
    gbc.fill = GridBagConstraints.BOTH;

    Panel.add(insertButton, gbc);

    // put the panel into the frame!
    setLayout(new BorderLayout());
    add(Panel, BorderLayout.CENTER);
    pack();
    setVisible(true);
}

问题是您没有将面板添加到顶级容器的内容窗格中。致电 this.add(panel) 让它发生。

此外,正如@MaddProgrammer 在他的评论中所说,您应该在添加所有组件后调用 pack()setVisible() 方法,否则您必须调用 revalidate()repaint() 以验证组件层次结构。

根据 Container#add(Component comp) 文档:

This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.

此外,您不应混用绝对布局调用,例如 setBounds()setLocation()setSize()(避免使用它们)和布局管理器(强烈推荐这些)