问题描述
好的,我阅读了Java文档,我无法弄清楚这两种方法之间的主要区别。有时我使用,有时,有时一个做我想要的,有时一个做另一个。
Ok, I read the Java Documentation and I just can't figure out what is the main difference between those two methods. Sometimes I used setSize()
, sometimes setPreferredSize()
, sometimes one does what I want, sometimes the other.
那么,两者之间的主要区别是什么?我应该使用哪一个 JFrames
和 JPanels
?
So, what is the main difference between the two? Which one should I use for JFrames
and JPanels
?
谢谢
推荐答案
简短的回答是:它很复杂。
The short answer is: it's complicated.
稍长的答案是:如果组件的父级没有布局管理器,则使用 setSize()
,并且 setPreferredSize()
并且其相关的 setMinimumSize
和 setMaximumSize
如果有。
The slightly longer answer is: use setSize()
if your component's parent has no layout manager, and setPreferredSize()
and its related setMinimumSize
and setMaximumSize
if it does.
setSize()
如果组件的父级使用布局管理器,则可能不会执行任何操作;通常会产生影响的地方是顶级组件( JFrames
和 JWindows
)以及在内滚动窗格
。如果你的父组件中没有布局管理器,你也必须调用 setSize()
。
setSize()
probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrames
and JWindows
) and things that are inside of scrolled panes
. You also must call setSize()
if you've got components inside a parent without a layout manager.
As一般规则, setPreferredSize()
如果您有布局管理器,应该做正确的事情;大多数布局管理器通过获取其组件的首选(以及最小和最大)大小,然后使用 setSize()
和 setLocation()来工作
根据布局规则定位这些组件。所以(作为例子) BorderLayout
将尝试使其北区域的边界等于首选大小
它的北部组件 - 它们可能会大于或小于它,具体取决于 jframe
的大小,布局中其他组件的大小,等等。
As a general rule, setPreferredSize()
should do the "right thing" if you've got a layout manager; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, and then using setSize()
and setLocation()
to position those components according to the layout's rules. So (as an example) a BorderLayout
will try to make the bounds of its "north" region equal to the preferred size
of its north component - they may end up larger or smaller than that, depending on the size of the jframe
, the size of the other components in the layout, and so on.
这篇关于Java:组件中setPreferredSize()和setSize()方法之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!