Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lightest-weight spacer component in a GridBagLayout

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.

like image 370
dcstraw Avatar asked Jun 01 '09 15:06

dcstraw


People also ask

Which of the GridBagLayout variable defines the external padding around the component?

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 .

What is Gridbag layout?

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.

Which layout class is used to align components vertically and horizontally or along their baseline?

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.


1 Answers

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

like image 193
banjollity Avatar answered Sep 21 '22 17:09

banjollity