How to push GridbagLayout not to lay components in the center of JPanel

In addition to setting the anchor and fill fields, you will likely need to set the weightx field. This helps specify resizing behavior.

Quote:

Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container. This is because when the weight is 0.0 (the default), the GridBagLayout puts any extra space between its grid of cells and the edges of the container.

The following will keep myComponent anchored to the NORTHWEST corner. Assuming this is JPanel or similar:

setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

// Specify horizontal fill, with top-left corner anchoring
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;

// Select x- and y-direction weight. Without a non-zero weight,
// the component will still be centered in the given direction.
c.weightx = 1;
c.weighty = 1;

// Add child component
add(myComponent, c);

To keep child components left-aligned yet vertically-centered, just set anchor = WEST and remove weighty = 1;.


You need to add at least one component that will fill the horizontal space. If you don't have such a component you can try this:

GridBagConstraints noFill = new GridBagConstraints();
noFill.anchor = GridBagConstraints.WEST;
noFill.fill = GridBagConstraints.NONE;

GridBagConstraints horizontalFill = new GridBagConstraints();
horizontalFill.anchor = GridBagConstraints.WEST;
horizontalFill.fill = GridBagConstraints.HORIZONTAL;    

panel.add(new JLabel("Left Aligned"), noFill);
panel.add(Box.createHorizontalGlue(), horizontalFill);