Search code examples
javaswinglayout-managergridbaglayout

GridBagLayout with buttons


I am trying to draw a panel with buttons, that looks something like this:

enter image description here

I create the "buttonPanel" like this:

buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0;
gbc.weighty = 0;

gbc.gridx = 0; gbc.gridy = 0;
gbc.gridwidth = 1; gbc.gridheight = 2;
buttonPanel.add(new JButton("A0"), gbc);

gbc.gridx = 1; gbc.gridy = 0;
gbc.gridwidth = 1; gbc.gridheight = 2;
buttonPanel.add(new JButton("A1"), gbc);

gbc.gridx = 2; gbc.gridy = 0;
gbc.gridwidth = 2; gbc.gridheight = 2;
buttonPanel.add(new JButton("A2"), gbc);

gbc.gridx = 0; gbc.gridy = 2;
gbc.gridwidth = 3; gbc.gridheight = 2;
buttonPanel.add(new JButton("A3"), gbc);

gbc.gridx = 3; gbc.gridy = 2;
gbc.gridwidth = 1; gbc.gridheight = 2;
buttonPanel.add(new JButton("A4"), gbc);

But the result looks like this:

enter image description here

As button "A3" has a gridwidth=3, it should reach the middle of button "A2"?

Any help?

Edit1: Increasing the panel size, or setting a longer text on the buttons, does not change anything:

enter image description here

Edit2: Setting the weightx=1 for button "A2" and "A3" helps:

enter image description here

This is acceptable for me, although it would be nice if button "A4" would have the same width as button "A0" and "A1"


Solution

  • Set for A2 and A3 the weightx to 1.0.