Well, I would say that almost always the right solution is to fix the layouting either by using a different layout manager, or by using a different hierarchy of containers (or both).
However, since it seems you won't be persuaded (I infer that from your question), I can suggest a solution to the specific question you ask (again, I would recommend to take a different path of fixing the layout, which probably is your real problem).
You can set the maximum height without affecting the maximum width, by overriding the setMaximumSize()
method as follows:
@Override
public void setMaximumSize(Dimension size) {
Dimension currMaxSize = getMaximumSize();
super.setMaximumSize(currMaxSize.width, size.height);
}
Another approach can be to keep the "overridden" setting of the max height, and return it when returning the maximum height, like so:
private int overriddenMaximumHeight = -1;
public void setMaximumHeight(int height) {
overriddenMaximumHeight = height;
}
@Override
public Dimension getMaximumSize() {
Dimension size = super.getMaximumSize();
int height = (overriddenMaximumHeight >=0) ? overriddenMaximumHeight : size.height;
return new Dimension(size.width, height);
}
Again (lastly), I would recommend taking a more common approach, but if you insist ...