views:

458

answers:

1

In a GridBagLayout, what component is the best for providing empty space in a panel? Ideally I would like to use a component that has:

  1. Low overhead
  2. No side effect when no empty space is required (i.e. no minimum size)
  3. A trivial constructor (no parameters)

A JPanel violates #2 above. A Box requires a constructor parameter (#3 above), which is really not necessary in this simple case. A JLabel works well but I worry that it may have some overhead, though admittedly it is probably pretty low.

An anonymous class also seems to work well (i.e. "new JComponent() { }"), but that adds an additional .class file every time I use it. I suppose it's no more overhead than any given event handler though. Would it be worth creating a custom, zero-implementation component derived from JComponent for this? Is there an existing component that I am missing?

FYI GridBagLayout is one of my constraints on the team I'm part of, so other layouts are not an option.

+1  A: 

You mention Box but it can be used in a "lightweight" fashion with the following four static methods that simply return a component. I use these all the time. They're invisible with respect to painting. In your case it looks like the glues are the way to go. A trivial constructor (like that's a bad thing!), low overhead. The side-effect when no space is required is all down to how you layout your gridbag.

panel.add( Box.createHorizontalGlue() );
panel.add( Box.createVerticalGlue() );
panel.add( Box.createHorizontalStrut( int width ) );
panel.add( Box.createVerticalStrut( int width ) );

JavaDoc here: http://java.sun.com/javase/6/docs/api/javax/swing/Box.html

banjollity
I like this solution very much. The "createGlue()" method also works well for my purposes. My only qualm with this is that it's intended for BoxLayouts, but I'll try to get over it and not be so picky. :)Thanks for the answer!
dcstraw
No need for qualms - from the JavaDoc: "Box provides several class methods that are useful for containers using BoxLayout -- even non-Box containers."
banjollity