Java Swing: How do I define one minimal dimension (of the two) for components?
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.setPreferre开发者_JS百科dSize(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).
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.
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...
精彩评论