I have to edit a gridbag layout problematically and i am having weird results.
expected:
| A | | B |
| -- | | C |
| D | | -- |
Results:
| A | | B |
| D | | C |
A and C have a height of 2
Is this just how gridbag works? is there anyway to force it?
My program has two columns and n number of rows. It supports a width of 2 but it only comes into effect when it is in the first col. If in the 2nd row it acts as though the width is 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;
the components are added by the user and the user determines the width and height. the gridxand gridy values are determined by what other components are added and placed.
The gridbag layout works fine for say
*_ _
|A|B|
|_|C|
it just doesn't seem to like it when C has a height of 2
解决方案
Now that the question has been clarified:
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);
}