Search code examples
javaarraysgridbaglayout

Fill GridBagLayout with Array Elements


I'm trying to build a Panel holding Elements of an Array using GridBagLayout. Creating the Elements works just fine. Problem is either the Layoutmanager is ignored or the Constraints aren't applied correctly, anyways the buttons are arranged as if there was no Layoutmanager at all. So what do i have to do so it looks like a table?

Thanks in advance!

Sidenote : No, JTable isn't an option. In my application only some of the buttons are actually created.

Edit: I found the problem. I simply forgot the line "setLayout(gbl);" Stupid me.

//(includes)

public class GUI {
    public static void main (String[] args) {
        JFrame frame = new JFrame();
        frame.add (new MyPanel(5, 4);
        frame.setVisible(true);
    }

    private class MyPanel () extends JPanel {
        public MyPanel (int x, int y) {
            GridBagLayout gbl = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            setLayout (gbl);

            JButton[][] buttons = new JButton[x][y];
            for (int i=0; i<x; i++) {
                for (int j=0; j<y; j++) {
                    buttons[i][j] = new JButton("a"+i+j);
                    gbc.gridx = j; gbc.gridy = i;
                    gbl.setConstraints(buttons[i][j], gbc);
                    add (buttons[i][j]);
                }
            }
        }
    }
}

Solution

  • You may also consider using a MigLayout, the code is simpler and easier to maintain:

    public class MyPanel extends JPanel {
        public MyPanel(int x, int y) {
            setLayout(new MigLayout("wrap " + x));
    
            JButton[][] buttons = new JButton[x][y];
            for (int i = 0; i < x; i++) {
                for (int j = 0; j < y; j++) {
                    buttons[i][j] = new JButton("a" + i + j);
                    add(buttons[i][j]);
                }
            }
        }
    }