Java:组件中的 setPreferredSize() 和 setSize() 方法之间的区别 [英] Java: Difference between the setPreferredSize() and setSize() methods in components

查看:23
本文介绍了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.

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.

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

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