I made a simple GridBagLayout that adds buttons to cells (0,0), (1,0) and (0,1).
JPanel panelMain = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; panelMain.add(new JButton("0,0"),c); c.gridx = 1; c.gridy = 0; panelMain.add(new JButton("1,0"),c); c.gridx = 0; c.gridy = 1; panelMain.add(new JButton("0,1"),c);
I was glad to see the final user interface:

I want to add a JButton to a cell that is not related to existing cells. I want to be divided into empty space. When I try to do this, the new JButton centered next to others. Here is the addition:
JPanel panelMain = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; panelMain.add(new JButton("0,0"),c); c.gridx = 1; c.gridy = 0; panelMain.add(new JButton("1,0"),c); c.gridx = 0; c.gridy = 1; panelMain.add(new JButton("0,1"),c); c.gridx = 3; c.gridy = 0; panelMain.add(new JButton("3,0"),c);
Output:

Cell (2.0) displays JButton("3,0") . Do I need to use an empty JPanel as a place holder in cell (2.0)? More importantly, why is this happening?
source share