Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does GridBagLayout require placeholder panels for empty cells?

I made a simple GridBagLayout which adds buttons in the 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 happy to see the resultant UI:

Desired result

I want to add a JButton in a cell that is not connected to the existing cells. I want it to be separated by an empty space. When I try this, the new JButton is lumped in next to the 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);

The output:

Undesired result

The JButton("3,0") is displaying at the cell (2,0). Do I need to use an empty JPanel as a place holder in the cell (2,0)? More importantly, why is this happening?

like image 908
baxdab Avatar asked Oct 04 '15 00:10

baxdab


2 Answers

Do I need to use an empty JPanel as a place holder in the cell (2,0)?

You can use an "insets" grid bag constraint to give space between components. Read the Swing tutorial on How to Use GridBagLayout for more information on the inset constraint.

Or, if you want to have a place holder then you can use a Box.createHorizontalStrut(...) to easily specify the width.

More importantly, why is this happening?

Cells don't have a size unless there is a component in the cell. Each cell is independent of one another so what size would you expect cell (2,0) to be?

like image 29
camickr Avatar answered Sep 21 '22 21:09

camickr


The layout does not know what should be the width to be left at 2,0 unless there is a component placed in the gridx = 2. By the time you complete the UI, if any component gets placed, it should look fine. For e.g.:

enter image description here

In other case you may add empty JPanel with background color matching to the background color of the container.

like image 168
James Jithin Avatar answered Sep 19 '22 21:09

James Jithin