Vince
Vince

Reputation: 15146

Set only maximum height for a panel (without using setMaximumSize) with GroupLayout

I looked around at all the other answers, but they all recommend to use GroupLayout, BoxLayout, or to wrap the panel that's using GridBagLayout with another panel that uses one of the layouts mentioned above.

I'm currently using GridBagLayout, and I'm wondering if there's a way to set the maximum height of a panel. I don't want a limit on width, only height, so setMaximumSize(Dimension) won't work.

Does GridBagLayout support this in any way? Sorry if my question doesn't contain any code, the only attempt I could possibly find is setMaximumSize(Dimension), or wrapping it in another panel (which I'm hoping to avoid)

Upvotes: 6

Views: 8380

Answers (2)

Oleg Estekhin
Oleg Estekhin

Reputation: 8395

If you want to limit only one dimension then just do not limit the other:

    component.setMaximumSize( new Dimension(
            Integer.MAX_VALUE,
            requiredMaxHeight
    ) );

Upvotes: 11

ethanfar
ethanfar

Reputation: 3778

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 ...

Upvotes: 2

Related Questions