Right now I don't understand, why GridBagLayout from Java does what it does.
What I expected:
What I got:
My code:
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LayoutTest extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
LayoutTest t = new LayoutTest();
t.setSize(640, 480);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setVisible(true);
}
public LayoutTest() {
JPanel content = new JPanel(new GridBagLayout());
addToPanel(content, createTestPanel(Color.CYAN), 0, 0, 1, 1, 0.5d, 1.0d);
addToPanel(content, createTestPanel(Color.BLUE), 1, 0, 2, 1, 1.0d, 1.0d);
addToPanel(content, createTestPanel(Color.CYAN), 3, 0, 1, 1, 0.5d, 1.0d);
addToPanel(content, createTestPanel(Color.YELLOW), 0, 1, 2, 1, 1.0d, 1.0d);
addToPanel(content, createTestPanel(Color.GRAY), 2, 1, 2, 1, 1.0d, 1.0d);
this.setContentPane(content);
}
private JPanel createTestPanel(Color c) {
JPanel ret = new JPanel();
ret.setBackground(c);
return ret;
}
private void addToPanel(JPanel target, JComponent component, int x, int y, int width, int height, double weightx, double weighty) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = x;
gbc.gridwidth = width;
gbc.weightx = weightx;
gbc.gridy = y;
gbc.gridheight = height;
gbc.weighty = weighty;
target.add(component, gbc);
}
}
Though I expected this code to create a layout where the blue rectangle has the same width as the yellow or the grey one whilst being centered in the upper row I don't seem to be able to make it work.
So why doesn't this work? What did I miss?