private static class ComponentDummy extends Component {
/** Serial version UID */
private static final long serialVersionUID = 2352800857938659323L;
private final Component delegate;
/**
* Creates a new <code>ComponentDummy</code>.
*
* @param delegate
*/
public ComponentDummy(Component delegate) {
this.delegate = delegate;
}
@Override
public int getBaseline(int width, int height) {
return delegate.getBaseline(width, height);
}
@Override
public BaselineResizeBehavior getBaselineResizeBehavior() {
return delegate.getBaselineResizeBehavior();
}
@Override
public Dimension getMaximumSize() {
return delegate.getMaximumSize();
}
@Override
public Dimension getMinimumSize() {
return delegate.getMinimumSize();
}
@Override
public Dimension getPreferredSize() {
return delegate.getPreferredSize();
}
@Override
public boolean isVisible() {
return delegate.isVisible();
}
}
/**
* Calculates all layout areas' bounds. This method is considered a
* heavy-weight regarding performance.
*
* @param parent the parent container
* @param layout the layout manager used
* @return a map of components (key) and area bounds (value)
*/
public static Map<Component, Rectangle> calculateGridBounds(
final Container parent,
GridBagLayout layout) {
final GridBagLayout dummyLayout = new GridBagLayout();
final Container dummyParent = new Container() {
/** Serial version UID */
private static final long serialVersionUID = 6222395303825422367L;
@Override
public Insets getInsets() {
return parent.getInsets();
}
};
dummyParent.setLayout(dummyLayout);
dummyParent.setBounds(parent.getBounds());
synchronized (parent.getTreeLock()) {
final int componentCount = parent.getComponentCount();
for (int i = 0; i < componentCount; i++) {
final Component comp = parent.getComponent(i);
GridBagConstraints gbc = layout.getConstraints(comp);
if (gbc == null) {
gbc = new GridBagConstraints();
}
gbc.fill = GridBagConstraints.BOTH;
dummyParent.add(new ComponentDummy(comp), gbc);
}
final Map<Component, Rectangle> bounds =
new IdentityHashMap<Component, Rectangle>();
dummyParent.doLayout();
for (int i = 0; i < componentCount; i++) {
ComponentDummy dummy = (ComponentDummy) dummyParent.getComponent(i);
bounds.put(dummy.delegate, dummy.getBounds());
}
return bounds;
}
}