Search code examples
javauser-interfacegridbaglayoutgaps-in-visuals

gridbadlayout vertical gaps


I'm making a panel with som buttons on it. this is what it looks like now.

But i want the buttons to touch each other, in other words, I want the vertical gaps to dissapear. But the buttons shouldn't be resized. How can I go ahead to do this?

My code:

this.setLayout(new GridBagLayout());
    GridBagConstraints constraints = new GridBagConstraints();

    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.gridwidth = 2;
    constraints.weightx = 1D;
    constraints.weighty = 1D;
    constraints.gridx = 0;
    constraints.gridy = 0;
    int row = 0;
    for (MainAction actie : mainActions) {
        constraints.gridy = row;
        row++;
        SelectedActionButton but = new SelectedActionButton(selectedActionModel, actie);
        this.add(but, constraints);

    }
    constraints.gridwidth = 1;
    constraints.weightx = 0.5D;
    row *=2;
    for (AbstractAction actie : objectActions) {
        constraints.gridy = row/2;
        constraints.gridx = row%2;
        row++;
        SelectedObjectButton but = new SelectedObjectButton(selectedObjectModel, actie);
        but.setMargin(new Insets(0, 0, 0, 0));
        this.add(but, constraints);
    }

thanks in advance


Solution

  • Change the following line

    constraints.weighty = 1D;
    

    to

    constraints.weighty = 0D;
    

    will fix your issue.

    Update: to align all buttons north you may add an additional component in the last row eating all available space:

    constraints.weighty = 1D;
    constraints.gridy = row;
    this.add(Box.createGlue(), constraints);