Search code examples
javaswinglayout-managergrid-layoutgridbaglayout

unable to add buttons vertically


I am writing a program where JButtons are added dynamically to a JPanel in a vertical fashion. (the buttons are stored in an arraylist)I have tried the following code by setting the JPanel to gridbaglayout.

        for(int i = 0; i<listOfButtons.size();i++) {
            c.gridx=0;
            c.gridy=i;
            leftButtonPanel.add(listOfButtons.get(i));
        }

the result is the following

enter image description here

and after adding the buttons

enter image description here

I have also tried setting the JPanel to a gridlayout

leftButtonPanel.setLayout(new GridLayout(listOfButtons.size(),1));

for(int i = 0; i<listOfButtons.size();i++) {
            leftButtonPanel.add(listOfButtons.get(i));
}

before adding

enter image description here

The buttons "see all" and "add" are all in the same listOfButtons arraylist. and the only way to add buttons into the panel is through that forloop. for some reasons the buttons still start off horizontally.


Solution

  • For GridBagLayout, don't forget, you need to supply the GridBagConstraints as well, otherwise it act a lot like a FlowLayout

    Water fall

    import java.awt.EventQueue;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class SoTest {
    
        public static void main(String[] args) {
            new SoTest();
        }
    
        public SoTest() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame();
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            public TestPane() {
                setLayout(new GridBagLayout());
    
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridwidth = GridBagConstraints.REMAINDER;
                gbc.fill = GridBagConstraints.HORIZONTAL;
    
                List<JButton> listOfButtons = new ArrayList<>(5);
                for (int i = 0; i < 10; i++) {
                    listOfButtons.add(new JButton(Integer.toString(i)));
                }
    
                for (int i = 0; i < listOfButtons.size(); i++) {
                    add(listOfButtons.get(i), gbc);
                }
            }
    
        }
    }
    

    At this point, I'm curious as to if you should be considering a JList instead