打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
swing 知识点
我以前很喜欢borderlayout的布局方式,每次想特别调整每个区域的大小,但是每次将一个panel放入到north或者其他4个区域时,总是达不到想要的效果,刚刚才发现原来setPreferredSize和setSize是有区别的。


The short answer is: it's complicated.
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() 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 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 frame, the size of the other components in the layout, and so on

上面大概意思说的就是:

1.setPreferredSize需要在使用布局管理器的时候使用,布局管理器会获取空间的preferredsize,因而可以生效。例如borderlayout在north中放入一个panel,panel的高度可以通过这样实现:panel.setPreferredSize(new Dimension(0, 100));这样就设置了一个高度为100的panel,宽度随窗口变化。

2.setSize,setLocation,setBounds方法需要在不使用布局管理器的时候使用,也就是setLayout(null)的时候可以使用这三个方法控制布局。
区分好这两个不同点之后,我相信你的布局会更随心所欲。
未设置Layout时,java默认为flowLayout布局的,设置为null即为清空布局管理器,之后添加组件,常常是设置组件左上角坐标相对于容器左上角(0,0)的x,y值来确定组件的位置,即使更改容器大小也不会改变位置。这种方式常常用于窗体大小固定的容器里。
Frame默认的是BorderLayout布局管理器
Panel默认的是FlowLayout布局管理器
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Java语言程序设计基础课件ppt第9章 第1讲
swt与awt/swing互嵌
Swing 之 Layout
Ext2.0布局类初步认识
(总结)Java图形界面编程知识点汇总(待补充)
java 中各种layout
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服