Buttons doesn't fill all available space when I use GridBagLayout in Java

1k Views Asked by At

I want to create an application with buttons arrayed into invisible table. The buttons should fill all the available space inside the imaginary cells even when I´ll resize the frame. I´m using Swing, GridBagLayout. I've read some articles and the solution was to add .weightx=1 and .weighty=1. Weightx works perfect and it fill the gaps but weighty doesn't. Buttons don´t extend into height of cell. Is there a problem with my code or is there something to add that solve my problem? Or should I use absolutely another layout?

public class NewClass {
  public void NewClass(){
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    frame.add(panel);
    GridBagLayout layout = new GridBagLayout();
    panel.setLayout(layout);
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;

    gbc.gridx = 0;
    gbc.gridy = 0;
    JButton B11 = new JButton("11");
    panel.add(B11,gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    JButton B12 = new JButton("12");
    panel.add(B12,gbc);

    gbc.gridx = 0;
    gbc.gridy = 1;
    JButton B21 = new JButton("21");
    panel.add(B21,gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    JButton B22 = new JButton("22");
    panel.add(B22,gbc);

    frame.pack();
    frame.setSize(800,400);
    frame.setVisible(true);
}}
1

There are 1 best solutions below

0
On BEST ANSWER

You're using the wrong GridBagConstraints#fill field value, since the value you're using is telling the layout manager to fill the buttons horizontally only.

You need to change

  gbc.fill = GridBagConstraints.HORIZONTAL;

to

  // gbc.fill = GridBagConstraints.HORIZONTAL;
  gbc.fill = GridBagConstraints.BOTH;

if you want the buttons to fill both directions, both horizontally and vertically.