Previous | Next | Trail Map | Creating a User Interface | Laying Out Components within a Container


General Rules for Using Layout Managers

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 are add(), remove(), removeAll(), layout(), preferredSize(), and minimumSize(). The add(), remove(), and removeAll() methods add and remove Components from a Container; you can call them at any time. The layout() 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]. The preferredSize() and minimumSize() 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() and minimumSize() 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's addNotify() method is called, which happens:


Previous | Next | Trail Map | Creating a User Interface | Laying Out Components within a Container