Search code examples
javaswingsizejcomponent

JComponent: how to set maximum width?


I need to make JComponent's width to be 300 or less, but height should be variable (depending on content of JComponent).

Firstly, I tried to use

myComponent.setMaximumSize(300, 9999);

but I found that this method has absolutely no effect, and component still becomes expanded depending on its content (I can't see any effect, at least).

Then I tried to use

myComponent.setPreferredSize(300, (int)myComponent.getPreferredSize().getHeight());

Then, width becomes 300 and not less than 300. This isn't perfect, but acceptable. BUT, now, when component's content is changed, size isn't changed! This isn't acceptable.

I tried to find the way to affect only preferred width, and leave height to be "default", but I failed to find that way.

I tried to set height to 0 or -1: no effect.

How to achieve that?


UPD: please take a look at the picture: http://goo.gl/3Hp59 That's what I already implemented, but I used setPreferredSize(), which is bad, as I already realized, thank you.

Please help me find out the correct way:

Currently I use GridBagLayout. I need to make right column's width <= 300. (and left one, say, <= 200) How to achieve that using GridBagLayout, or what layout should I use instead?


Solution

  • Use GroupLayout. It has some the best controls for sizing. GroupLayout can look a bit intimidating, but the examples provided are excellent. Especially useful if you want to allow the user to resize the screen.