Does GridBagLayout require placeholder panels for empty cells?

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:

Desired result

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:

Undesired result

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?

+5
source share
2 answers

The layout does not know what the width remaining at 2,0 should be if gridx = 2 does not have a component. By the time the user interface is complete, if any component is hosted, it should look normal. For example, for example:

enter image description here

Alternatively, you can add an empty JPanel with a background color matching the background color of the container.

+3
source

Do I need to use an empty JPanel as a place holder in cell (2.0)?

You can use "mesh" mesh bag constraints to provide space between components. Read the Swing tutorial on How to Use GridBagLayout for more information on insert restriction.

Or, if you want to have a seat holder, you can use Box.createHorizontalStrut(...) to easily indicate the width.

More importantly, why is this happening?

Cells are not sized if there is no component in the cell. Each cell is independent of each other, and what size do you expect from a cell (2.0)?

+2
source

Source: https://habr.com/ru/post/1232875/


All Articles