Search code examples
javaswinglayout-managergridbaglayout

Java Swing GridBagLayout - adding buttons without space


How can I remove spacing caused by gridBagLayout and make them stick together?
Here is my code simply adding 3 buttons. I read this question but there was no complete solution How to fix gap in GridBagLayout;
I just want to put all of my buttons on the top of the JFrame.

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyProblem {

    private JFrame frame = new JFrame();

    public static void main(String[] args) {
        new MyProblem();
    }

    public MyProblem() {
        frame.setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();
        gc.weightx = 1;
        gc.weighty = 1;
        gc.gridx = 0;
        gc.gridy = 0;
        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.anchor = GridBagConstraints.NORTH;
        for (int i = 0; i < 3; i++) {
            JPanel jPanel = new JPanel(new BorderLayout());
            jPanel.setSize(80, 80);
            jPanel.add(new JButton("Button " + i),BorderLayout.PAGE_START);
            frame.add(jPanel, gc);
            gc.gridy++;
        }

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

}

How my buttons look like:
enter image description here
How I want my buttons to look like: enter image description here


Solution

  • This code will do the job:

    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    
    import javax.swing.Box;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    
    public class MyProblem {
    
        private JFrame frame = new JFrame();
    
        public static void main(String[] args) {
            new MyProblem();
        }
    
        public MyProblem() {
            frame.setLayout(new GridBagLayout());
            GridBagConstraints gc = new GridBagConstraints();
            gc.weightx = 1;
            gc.weighty = 0;
            gc.gridx = 0;
            gc.gridy = 0;
            gc.ipadx = 0;
            gc.ipady = 0;
            gc.fill = GridBagConstraints.HORIZONTAL;
            gc.anchor = GridBagConstraints.NORTH;
            for (int i = 0; i < 3; i++) {
                JButton button = new JButton("Button " + i);
                frame.add(button, gc);
                gc.gridy++;
            }
            gc.weighty = 1;
            frame.add(Box.createGlue(), gc); //Adding a component to feel the area.
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(500, 500);
            frame.setVisible(true);
        }
    
    }