我想使用 GridBagLayout 用 Java 制作一个 GUI。这就是我最终想要的:
因此,我按照我在互联网上找到的一些说明进行操作,这是我编写的代码:
Panel panel = new Panel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.BOTH;
gc.insets = new Insets(5, 5, 5, 5);
gc.weightx = 7;
gc.weighty = 7;
panel.add(new JLabel("title"), gc, 0, 0, 2, 1);
panel.add(new JButton("button 1"), gc, 2, 0, 1, 1);
panel.add(new JButton("button 2"), gc, 3, 0, 1, 1);
panel.add(new JButton("button 3"), gc, 4, 0, 1, 1);
panel.add(new JButton("button 4"), gc, 5, 0, 1, 1);
panel.add(new JButton("button 5"), gc, 6, 0, 1, 1);
panel.add(new JLabel("subtitle"), gc, 0, 1, 7, 1);
panel.add(new JButton("list"), gc, 0, 2, 2, 4);
panel.add(new JButton("button"), gc, 0, 6, 1, 1);
panel.add(new JButton("button"), gc, 1, 6, 1, 1);
panel.add(new JButton("table"), gc, 2, 2, 5, 5);
我的功能添加:
public void add(Component component, GridBagConstraints constraints, int x, int y, int width, int height) {
constraints.gridx = x;
constraints.gridy = y;
constraints.gridwidth = width;
constraints.gridheight = height;
this.add(component, constraints);
}
但是,我最后有这个:
如您所见,表格的高度根本不占用 5 个单元格,列表也不占用 4 个单元格。有人知道为什么会这样吗?谢谢你。