Laying Out Components within a Container |
Unless you explicitly tell a Container not to use a layout manager, it will be associated with its very own instance of a layout manager. This layout manager is automatically consulted every time the Container might need to change its appearance. Except for GridBagLayout, most layout managers don't require applications and applets to directly call the layout manager's methods.How to Create a Layout Manager and Associate It with a Container
Every container has a default layout manager associated with it. If you want to use this default, you don't have to do a thing. The constructor for each Container creates a layout manager instance and initializes the Container to use it.To use a non-default layout manager, you need to create an instance of the desired layout manager class and tell the Container to use it. Below is some typical code that does this. This code creates a CardLayout manager and sets it up as the layout manager for a Container.
aContainer.setLayout(new CardLayout());Rules of Thumb for Using Layout Managers
The Container methods that result in calls to the Container's layout manager areadd()
,remove()
,removeAll()
,layout()
,preferredSize()
, andminimumSize()
. Theadd()
,remove()
, andremoveAll()
methods add and remove Components from a Container; you can call them at any time. Thelayout()
method, which is called as the result of any paint request to a Container, requests that the Container place and size itself and the Components it contains; you don't call it directly [CHECK]. ThepreferredSize()
andminimumSize()
methods return the Container's ideal size and minimum size, respectively. The values returned are just hints; they have no effect unless your program enforces these sizes [CHECK].You must take special care when calling a Container's
preferredSize()
andminimumSize()
methods. The values these methods return are meaningless unless the Container and its Components have valid peer objects. The peer object corresponding to a Component is created whenever the Component'saddNotify()
method is called, which happens:
- when the Component is a peer-less Window, or is contained in a peer-less Window, and the Window's
pack()
orshow()
method is called- when the Component is added to a Container that already has a peer
- when your program directly calls the Component's
addNotify()
method, or theaddNotify()
method of any Container above the Component [is this really OK?]
Laying Out Components within a Container |