Laying Out Components within a Container |
Problem: How do I specify a component's exact size?
- 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 whose contents do not change size (such as images), specifying the exact size makes sense. For custom components, you need to override the
Component
getMinimumSize
andgetPreferredSize
methods to return the correct size of the component. You can also override thegetMaximumSize
method to return the largest reasonable size of the component. Next, be sure that your component's container uses a layout manager that respects the specified size of the component.To change the size of a component that's already been displayed, see the next problem.
Problem: How do I resize a component?
Note: All component sizes are subject to layout manager approval. TheFlowLayout
andGridBagLayout
layout managers use the component's natural size (the latter depending on the constraints that you set), butBorderLayout
andGridLayout
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
setSize
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
getPreferredSize
andgetMinimumSize
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 |