Laying Out Components within a Container |
Problem: How do I specify a component's exact size?Problem: How do I resize a component?
- First, make sure that you really need to set the component's exact size. The standard components have different sizes, depending on the platform they're running on and the font they use, so it usually doesn't make sense to specify their exact size.
For custom components that have fixed-size contents (such as images), specifying the exact size makes sense. For custom components, you need to override the Component
minimumSize()
andpreferredSize()
methods to return the correct size of the component.To change the size of a component that's already been displayed, see the next problem.
Note: All component sizes are subject to layout manager approval. The FlowLayout and GridBagLayout layout managers use the component's natural size (the latter depending on the constraints that you set), but BorderLayout and GridLayout usually don't. Other options are writing or finding a custom layout manager or using absolute positioning.
Problem: My custom component is being sized too small.
- Once a component has been displayed, you can change its size using the Component
resize()
method. You then need to call thevalidate()
method on the component's container to make sure the container is laid out again.
- Does the component implement the
preferredSize()
andminimumSize()
methods? If so, do they return the right values?- Are you using a layout manager that can use as much space as is available? See General Rules for Using Layout Managers 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, see Common Component Problems.
Laying Out Components within a Container |