Swing QuickTip: The Totally GridBag Fix(20:31, 02. Jun. 2011)

Maybe you already know the GridBagLayout issue for collapsing components described in bug report 4328923 and we really love the related Totally GridBag cartoon for years. Because of the popularity of the clip it's finally time to bring some light into the shadow and show how to fix the issue.

GridBagLayout Fix

First of all the issue only occurs if no fill constraint is set. However, sometimes you want the preferred size to be respected and therefore you initialize TextFields with a default text or a column number. GridBagLayout falls back to use the minimum layout size of a component if there's not enough space to display a component with it's preferred size - this leads to the well known collapsing effect for text components. A workaround is to override #getMinimumSize() of related components and to return the preferred size instead. Unfortunately this also means that you have to touch many components for fixing.

Workaround - PreferredGridBagLayout

Our recommended workaround is pretty simple - create a custom GridBagLayout and override #getLayoutInfo() to force usage of the preferred component size.

public class PreferredGridBagLayout extends GridBagLayout
{
  @Override
  protected GridBagLayoutInfo getLayoutInfo(Container parent, int sizeflag)
  {
    return super.getLayoutInfo(parent, PREFERREDSIZE);
  }
}

Download Demo Sourcecode

Related Links

Totally GridBag Clip
Sun Bug Report #4238932
Swing QuickTip: Default Button