我必须编辑一个有问题的网格布局,我的结果很奇怪
预计:
| A | | B |
| - | | C |
| D | | - |
结果:
| A | | B |
| D | | C |
A和C的高度为2 这是格子袋的工作原理吗?无论如何迫使它?
我的程序有两列和n行。它支持2的宽度,但只有在第一个col时它才会生效。如果在第2行,它就像宽度为1一样。
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(7, 7, 7, 7);
gbc.weightx = 0.5;
gbc.anchor = GridBagConstraints.NORTH;
组件由用户添加,用户确定width
和height
。 gridx
和gridy
值取决于添加和放置的其他组件。
格子袋布局适用于说
* _ _
| A | B |
| _ | C |
当C的高度为2
答案 0 :(得分:1)
确保为正在使用的GridbagConstraints.BOTH
对象的fill
属性设置GridbagConstraints
。否则,您将无法在多行上拥有组件。
GridbagConstraints c = new GridbagConstraints();
c.fill = GridbagConstraints.BOTH;
答案 1 :(得分:1)
现在问题已经澄清了:
protected static final Insets entryInsets = new Insets(0, 10, 4, 10);
protected static final Insets spaceInsets = new Insets(10, 10, 4, 10);
protected void createPartControl() {
panel = new JPanel();
panel.setLayout(new GridBagLayout());
int gridy = 0;
gridy = createTextFields(gridy);
}
protected int createTextFields(int gridy) {
JLabel a = new JLabel("A");
a.setHorizontalAlignment(SwingConstants.LEFT);
addComponent(panel, a, 0, gridy, 1, 2, spaceInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel b = new JLabel("B");
b.setHorizontalAlignment(SwingConstants.LEFT);
addComponent(panel, b, 1, gridy++, 1, 1, spaceInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel c = new JLabel("C");
c.setHorizontalAlignment(SwingConstants.LEFT);
addComponent(panel, c, 1, gridy++, 1, 1, entryInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel d = new JLabel("D");
d.setHorizontalAlignment(SwingConstants.LEFT);
addComponent(panel, d, 0, gridy++, 2, 1, entryInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
return gridy;
}
protected void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight,
Insets insets, int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}