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:
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.
Padding and Insets Padding is determined by the ipadx and ipady fields of GridBagConstraints . They specify horizontal and vertical “growth factors” for the component. In Figure 19-11, the West button is larger because we have set the ipadx and ipady values of its constraints to 25 .
GridBagLayout is one of the most flexible — and complex — layout managers the Java platform provides. A GridBagLayout places components in a grid of rows and columns, allowing specified components to span multiple rows or columns.
Class GridBagLayout. The GridBagLayout class is a flexible layout manager that aligns components vertically, horizontally or along their baseline without requiring that the components be of the same size.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With