views:

45

answers:

2

To define minimal size successfully, I have to do the following:

// setting minimal width AND height
Dimension min = new Dimension(100, 100);
comp.setMinimumSize(min);
comp.setPreferredSize(min);
comp.setSize(min);

When I left one line out it doesn't work, which is strange, but it's not the point.

What do I do to limit just one of two dimensions (width or height) and let the component and/or the layout manager decide automatically about the unspecified dimension?

When I use a very small value for that dimension which I don't want to limit, many components are displayed wrong (i.e. too small).

+3  A: 

By default (i.e. if setMinimumSize has not been called on the component) getMinimumSize delegates to the component's layout manager, so you can try to redefine the getMinimumSize method as follows:

public Dimension getMinimumSize()
{
    return new Dimension(minWidth, super.getMinimumSize().height);
}

If you do this, remember that you should not call setMinimumSize on the component.

Grodriguez
I don't understand: you mean I should override `getMinimumSize` of the component, or do you mean the layout manager? Thanks!
java.is.for.desktop
Override the method in the component. It will delegate to the layout manager as long as `setMinimumSize` has not been called on the component. By overriding the way I described you get "default behavior" for height, but you can specify a minimum width explicitly.
Grodriguez
A: 

I propose an approach by myself:

For layout managers which align everything one axis (such as BoxLayout), one can specify "undefined dimension" set to Integer.MAX. It is strange, but it works. It seems that the axis which is opposite to the alignment axis is ignored (unless it's too small, as mentioned in the question).

private final static int UNSPECIFIED_DIMENSION = Integer.MAX_VALUE;

public static void setMinimalDimension(Component comp, int width, int height) {
  Dimension dim = new Dimension(width, height);
  comp.setMinimumSize(dim);
  comp.setPreferredSize(dim);
  comp.setSize(dim);
}

public static void setMinimalWidth(Component comp, int width) {
  setMinimalDimension(comp, width, UNSPECIFIED_DIMENSION);
}

public static void setMinimalHeight(Component comp, int height) {
  setMinimalDimension(comp, UNSPECIFIED_DIMENSION, height);
}

Works, as mentioned, with axis-aligning layout managers.

Yes, there goes another mystery of Java Swing...

java.is.for.desktop