JComponent:如何设置最大宽度? [英] JComponent: how to set maximum width?

查看:31
本文介绍了JComponent:如何设置最大宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使 JComponent 的宽度小于等于 300,但高度应该是可变的(取决于 JComponent 的内容).

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

首先,我尝试使用

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

然后我尝试使用

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

然后,宽度变为 300 且不小于 300.这并不完美,但可以接受.但是,现在,当组件的内容改变时,大小不会改变!这是不可接受的.

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.

我尝试将高度设置为 0 或 -1:无效.

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

如何实现?

UPD:请看图:http://goo.gl/3Hp59 这就是我已经实现,但我使用了 setPreferredSize(),这很糟糕,因为我已经意识到,谢谢.

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:

目前我使用 GridBagLayout.我需要使右列的宽度 <= 300.(和左一列,例如 <= 200)如何使用 GridBagLayout 实现这一点,或者我应该使用什么布局?

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?

推荐答案

使用 组布局.它有一些最好的尺寸控制.GroupLayout 可能看起来有点吓人,但提供的示例非常好.如果您想允许用户调整屏幕大小,则特别有用.

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.

这篇关于JComponent:如何设置最大宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆