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

2

5

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)

Ay answered 20/5, 2014 at 5:36 Comment(1)
Remember, sizing hints are just that, hints. Layout managers can ignore them...Prattle
M
10

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

    component.setMaximumSize( new Dimension(
            Integer.MAX_VALUE,
            requiredMaxHeight
    ) );
Moonseed answered 20/5, 2014 at 6:4 Comment(1)
This... this is actually a great solution!Androw
M
2

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

Melanson answered 20/5, 2014 at 5:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.