Solving Common Layout Problems

 <  Day Day Up  >  

Problem: How do I specify a component's exact size ?

Solution: First make sure that you really need to set it. Each Swing component has a different preferred size depending on the font it uses and the look and feel. For this reason, it often doesn't make sense to specify a component's exact size.

If the component isn't controlled by a layout manager, you can set its size by invoking the setSize or setBounds method on it. Otherwise, you need to provide size hints and then make sure you're using a layout manager that respects them.

If you extend a Swing component class, you can give size hints by overriding the component's getMinimumSize , getPreferredSize , and getMaximumSize methods . What's nice about this approach is that each get Xxxx Size method can get the component's default size hints by invoking super.get Xxxx Size() . Then it can adjust the size, if necessary, before returning it.

Another way to give size hints is to invoke a Swing component's setMinimumSize , setPreferredSize , and setMaximumSize methods.

Note: No matter how you specify your component's size, be sure that its container uses a layout manager that respects the requested size. The FlowLayout , GridBagLayout , and SpringLayout managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout and GridLayout usually don't. The BoxLayout manager generally uses a component's preferred size (although components can be larger) and is one of the few layout managers that respect the component's maximum size. If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.


Problem: My custom component is being sized too small.

Solution: Does the component implement the getPreferredSize and getMinimumSize methods? If so, do they return the right values? Can your layout manager use as much space as is available? See the section How Layout Management Works (page 97) in Chapter 4 for some tips on choosing a layout manager and specifying that it use the maximum available space for a particular component.

If you don't see your problem in this list, refer to Solving Common Component Problems (page 735).

 <  Day Day Up  >  


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net