【Swing基礎】setPreferredSize和setSize的區別及用法

首先看 @那十無憂 的【Swing基礎】佈局管理器 - LayoutManager
http://tieba.baidu.com/p/2101752057

我以前很喜歡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)的時候可以使用這三個方法控制佈局。


區分好這兩個不同點之後,我相信你的佈局會更隨心所欲。


英文來源:http://stackoverflow.com/questions/1783793/java-difference-between-the-setpreferredsize-and-setsize-methods-in-compone

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章