Extreme112
Extreme112

Reputation: 95

Set Components in Alternating Columns GridBagLayout

Is there a way to set components in alternating columns 0, 2, 4, 6 without filling 1, 3, 5 with an empty component in a GridBagLayout using GridBagConstraints?

The example in Java here sets the 5th button to start on column 1, but maybe because the rows above it were set already?
https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

Upvotes: 0

Views: 63

Answers (2)

Zak
Zak

Reputation: 114

You can define your GridBagLayout with row heights and column widths

int[]  rowHeights = new int[] { 50, 50, 50};
int[] columnWidths = new int[] { 100, 100, 100, 100, 100};
GridBagLayout layout = new GridBagLayout();
layout.rowHeights = rowHeights;
layout.columnWidths = columnWidths;

Add the components using GridBagConstraint as below

    JPanel panel = new JPanel();
    panel.setLayout(layout);

    JLabel label1 = new JLabel("Label 1");
    JLabel label2 = new JLabel("Label 2");
    JLabel label3 = new JLabel("Label 3");

    panel.add(label1,  new GridBagConstraints(
            0, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 
            new Insets(0,0, 0, 0), 0, 0));

    panel.add(label2,  new GridBagConstraints(
            2, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 
            new Insets(0,0, 0, 0), 0, 0));

    panel.add(label3,  new GridBagConstraints(
            4, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 
            new Insets(0,0, 0, 0), 0, 0));

Upvotes: 1

camickr
camickr

Reputation: 324147

Is there a way to set components in alternating columns 0, 2, 4, 6 without filling 1, 3, 5 with an empty component in a GridBagLayout

No. If a component isn't defined for a cell then basically its size is 0.

The layout can't guess what size you expect the "empty column" to be.

Maybe you can use the "insets" constraint to give space between columns.

Upvotes: 2

Related Questions