You should never use this method!!! The preferred size of a component should always be computed. This size information is based on several factors, including (but not limited to) The size of any fonts involved
The text that might appear in a component
Settings such as number of rows or columns
The amount of data in a component
The look and feel in question
Borders that have been applied to a component
The layout manager that's managing the contents of a container
The size of an image to be displayed in a component
If you override the preferred size of a component by calling setPreferredSize(), you don't allow the component to compute the size it needs, and stand a great chance of either having contents inside the component chopped or having extra room in the component. Note that getPreferredSize() will only be called by certain layout managers. If a component is not appearing the proper size, make sure all containers above it (that contain it) are using a layout manager. For more details on layout management and the effect of preferred size, please see my article "Effective Layout Management" at http://java.sun.com/jdc/onlineTraining/GUI/AWTLayoutMgr/
The text that might appear in a component
Settings such as number of rows or columns
The amount of data in a component
The look and feel in question
Borders that have been applied to a component
The layout manager that's managing the contents of a container
The size of an image to be displayed in a component
If you override the preferred size of a component by calling setPreferredSize(), you don't allow the component to compute the size it needs, and stand a great chance of either having contents inside the component chopped or having extra room in the component. Note that getPreferredSize() will only be called by certain layout managers. If a component is not appearing the proper size, make sure all containers above it (that contain it) are using a layout manager. For more details on layout management and the effect of preferred size, please see my article "Effective Layout Management" at http://java.sun.com/jdc/onlineTraining/GUI/AWTLayoutMgr/
不推荐使用setPreferredSize()组件的大小是可以通过计算得到,也可以通过这个方法指定通过计算得到的大小,是最优化的如果指定了大小,一旦组件所处的环境发生变化(例如添加了新的组件、布局管理器发生变化等),你的组件不会自动调整
JPanel的默认首选大小是10*10的,就算setSize也不能改变首选大小,
所以如果在JPanel里setSize一个大小,然后在JFrame里pack()的话最后的窗体大小还是10*10的。
这说明pack()应该是根据首选大小来压缩窗体的。所以如果根据JPanel的大小来pack()框架的大小就要在JPanel里用到setPreferredSize。
这都是我自己试出来的不是什么书上写的所以可能有不准确的地方,还有我还是不知道setPreferredSize和setSize()的关系。难道一个容器有两个尺寸标准?