本文介绍了Java:组件中 setPreferredSize() 和 setSize() 方法的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

我应该对 JFrameJPanel 使用什么调用?

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.

这篇关于Java:组件中 setPreferredSize() 和 setSize() 方法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:04