java - GridBagLayout 中未显示的元素

标签 java swing layout-manager gridbaglayout

我使用 GridBagLayout 作为 JFrame 布局。无论我写什么,我的元素都不会显示。请不要给出使用 GridBagLayout 以外的任何内容的答案(抱歉,如果这听起来很粗鲁)

enter image description here

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




    }

最佳答案

问题是您没有将面板添加到顶级容器的内容 Pane 中。调用 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()(只需避免它们)和布局管理器(强烈推荐这些)

关于java - GridBagLayout 中未显示的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35187039/

相关文章:

java - JTable 需要刷新才能显示更改

java - 元素不会出现在具有 GridLayout 或 FlowLayout 的面板中,但具有 setBounds 时它们会出现在面板中

java - JLabel.setVisible(false) 使其他组件的位置改变

java - Neo4j Java api无法通过关系类型中的全文索引获取关系

java.lang.NoClassDefFoundError : org/hibernate/criterion/Criterion 错误

java - 获取 equals 函数中使用的所有实例字段的名称

Java Swing - 按钮不会显示,直到光标悬停在它上面

java多级JPopupMenu

java - 框架中面板的固定尺寸

java - 匿名内部类在访问其原语等时是否总是捕获对 "this"(外部)对象的引用?