jGuru
Register Email     Password Forgot your
password?
HOME FAQS FORUMS DOWNLOADS ARTICLES PEERSCOPE LEARN

  Search   jGuru Search Help

Question What is the use of setPreferredSize() method for components?
Derived from A question posed by Mahesh chandra Puvvada
Topics Java:API:Swing, Java:API:AWT:Layouts
Author Scott Stanchfield
Created Oct 25, 2000 Modified Oct 26, 2000


Answer

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/

Is this item helpful?  yes  no     Previous votes   Yes: 2  No: 0



Comments and alternative answers

Comment on this FAQ entry

I use setPreferredSize() along with setMinimumSize()...
Neil Weber, Jan 5, 2001
I use setPreferredSize() along with setMinimumSize() and setMaximumSize() when I want to force a component to a specific size regardless of its contents. This is particularly useful for making all the buttons in a panel the same width or making multiple textfields in the same form the same width.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
As stated in my original answer, calling setPrefer...
Scott Stanchfield, Jan 7, 2001

As stated in my original answer, calling setPreferredSize() to explicitly set the size of your components is a very bad idea.

Always keep in mind that you have no control over actual font sizes or window/screen sizes on a computer that executes your application. Users can change things, and not all computers have the same environment.

Also, if you do something like


JButton b1 = new JButton("Hello");
JButton b2 = new JButton("A");

b2.setPreferredSize(b1.getPreferredSize());
b2.setMaximumSize(b1.getMaximumSize());

which is what I'd assume you're doing, you're asking for big trouble if b1 changes size.

Keep in mind that the statement


b2.setPreferredSize(b1.getPreferredSize());

is a one-shot setting of the size. It determines the current preferred size of b1, and sets b2's preferred size to that. If b1 changes, there is no effect on b2.

If you want adjacent components to be the same size, you should place them in a GridLayout. If the components are not adjacent, you'll need to nest the layouts to achieve the proper results.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  

Using a GridLayout is rarely possible. Think about...
Neil Weber, Jan 8, 2001
Using a GridLayout is rarely possible. Think about how you would do this within a GridBagLayout or the buttons of a JOptionPane.

For my uses of setPreferredSize(), the one shot behavior is usually the desired behavior.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  

I don't agree. Like I stated, GridLayout is very e...
Scott Stanchfield, Jan 11, 2001  [replies:1]

I don't agree. Like I stated, GridLayout is very effective for adjacent components.

For example, suppose you wanted to have dialog buttons all the same size:


  JPanel [BorderLayout]
    SOUTH=JPanel [FlowLayout(RIGHT)]
      JPanel [GridLayout(1,0,5,5)]
        JButton("Yes")        
        JButton("No")
        JButton("Cancel")

Works perfectly -- all buttons are the same size as the largest.

To do non-adjacent buttons is a bit trickier. BarfBagLayout will help, but it's overly complex. Other folks have created layout managers, some that act similar to HTML tables, some others, that can help size components.

A really great alternative is to delegate your getPreferredSize() method to another object. The other object looks at all components it controlls and returns the maximum real preferred size for all of them.

For example

Sizer (interface)

  • requires getRealPreferredSize()

SizerJButton (extends JButton, implements Sizer)

  • getRealPreferredSize() --> return super.getPreferredSize()
  • getPreferredSize() --> return sizeGroup.getPreferredSize()

SizeGroup (extends Object)

  • add(Sizer s) --> keep track of component
  • getPreferredSize() --> look at max getRealPreferredSize() of all added components
  • remove(Sizer s)

This is a very simple extension of whatever components you want, making it easy to set matching sizes.

The main advantage is that if any of the watched components changes (like font, text, etc), the preferredSize of all other watched components is likewise affected.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  

Re: I don't agree. Like I stated, GridLayout is very e...
James Rome, Jun 17, 2002
I use buttons to represent network nodes for a large intrenet site. They need to be the same size, and are draggable by the user, hence the layout manager is null. I need to set the size of my JButtons so they are all the same. If the text gets clipped, so be it.

I also need to have the wires that attach the nodes to be anchored on the buttons, and this is a lot easier and faster (with thousands of buttons) oif the sizes are all the same!

I never call getPreferredSize(). I just set it to the size I need.

However, if I use the Motif L&F, the buttons completely seem to ignore my calls to setPreferredSize and setMinimumSize and I get buttons that are the height of the text fields.



Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  

A component using its own setPreferredSize method?
Andrew West, Mar 11, 2004  [replies:1]

When a component observes an event that requests for a change of the preferredSize, why should it not use its own setPreferredSize operation to establish its new preferredSize?

This way, the preferredSize will always be computed, when necessary. What would be wrong with that?



Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: A component using its own setPreferredSize method?
Strelok Strelok, Apr 18, 2005
I call setPreferredSize b/c with GridBagLayout it's the only way to get the behaviour I need. I use this method to set all of the buttons the same size, there's no harm in it at all.
    /** 
     * Sets given components preferred size and minimum width to the same as
     * the one with the max preferred size.
     * 
     * @param comps JComponent[] the components who's size is
     *  checked and set.
     */
    private static void setAllToBiggestWidth(JComponent... comps) {
        Dimension widest = null;
        for (JComponent comp : comps) {
            Dimension dim = comp.getPreferredSize();
            assert dim != null;
            if (widest == null || dim.width > widest.width) {
                widest = dim;
            }
        }
        for (JComponent comp : comps) {
            assert widest != null;
            comp.setPreferredSize(widest);
            comp.setMinimumSize(widest);
        }
    }


Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  


Ask A Question



 
Related Links

Swing FAQ

Swing Forum

Sun's Swing Home Page

The Swing Connection

Swing in the Java Tutorial

Swing Short Course, part I

Swing Short Course, part II

AWT FAQ

AWT Forum

Sun's AWT Home Page

The Java Tutorial (Good AWT & Swing Coverage)

Effective Layout Management

Layout Manager Launch

Creating a Custom Layout Manager

Drag and Drop resources

Wish List
Features
About jGuru
Contact Us

 



The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers