我使用 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);
}
最佳答案
问题是您没有将面板添加到顶级容器的内容 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/