What is the use of setPreferredSize() method for components?

Scott Stanchfield

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/