Java:组件中的 setPreferredSize() 和 setSize() 方法之间的区别

2022-01-24 00:00:00 java swing jpanel jframe

setSize()setPreferredSize() 的主要区别是什么.有时我使用 setSize(),有时是 setPreferredSize(),有时一个做我想做的,有时另一个做.

What is the main difference between setSize() and setPreferredSize(). Sometimes I used setSize(), sometimes setPreferredSize(), sometimes one does what I want, sometimes the other.

JFrames 和 JPanels 应该使用什么调用?

What call should I use for JFrames and JPanels?

推荐答案

使用取决于组件的父级是否有布局管理器.

Usage depends on whether the component's parent has a layout manager or not.

  • setSize() -- 在父布局管理器不存在时使用;
  • setPreferredSize()(还有它的相关setMinimumSizesetMaximumSize)——当父布局管理器存在时使用.
  • setSize() -- use when a parent layout manager does not exist;
  • setPreferredSize() (also its related setMinimumSize and setMaximumSize) -- use when a parent layout manager exists.

如果组件的父级使用布局管理器,setSize() 方法可能不会做任何事情;这通常会产生影响的地方是顶级组件(JFrames 和 JWindows)以及滚动窗格内的东西.如果父组件中有没有布局管理器的组件,您还必须调用 setSize().

The setSize() method 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.

通常,如果存在布局管理器,setPreferredSize() 将按预期布局组件;大多数布局管理器通过获取其组件的首选(以及最小和最大)大小来工作,然后使用 setSize()setLocation() 来定位这些组件布局规则.

Generally, setPreferredSize() will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize() and setLocation() to position those components according to the layout's rules.

例如,一个 BorderLayout 试图设置它的北"边界.区域等于其北部组件的首选大小——它们最终可能大于或小于该大小,具体取决于 JFrame 的大小、布局中其他组件的大小等等开.

For example, a BorderLayout tries 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.

相关文章