## Layouts

We have seen some simple examples that show how to size or position child widgets based on the size of the parent. So far, this kind of computation has occurred in response to a resize listener. This is often the best way to handle simple widget positioning. However, there are common patterns used by applications when placing widgets. These patterns can be structured as configurable layout algorithms that can be reused by many different applications.

SWT defines layouts that provide general purpose positioning and sizing of child widgets in a composite. Layouts are subclasses of the abstract class Layout. The SWT standard layouts can be found in the org.eclipse.swt.layout package.

You should understand some general definitions when resizing and positioning widgets:

- The location of a widget is its x,y coordinate location within its parent widget.
- The preferred size of a widget is the minimum size needed to show its content. This is computed differently for each kind of widget. In the case of a composite, the preferred size is the minimum size that contains the composite and all of its children at their preferred sizes.
- The clientArea is the size of a widget's content area.
- The trim is the distance between a widget's client area and its actual border. Trim is occupied by the widget's borders or extra space at its edge. The size and appearance of the trim is widget and platform dependent.

These concepts are relevant for applications regardless of whether a layout is used. You can think of a layout as a convenient way to package resize functionality for reuse.

Some additional concepts are introduced by layouts:

- Some layouts support spacing between widgets in the layout.
- Some layouts support a margin between the edge of the layout and the widget adjacent to the edge.

See Understanding layouts in SWT for further discussion and pictures demonstrating these concepts.

The following code snippet shows the simple case of an application using a resize callback to size a label to the size of its parent shell:

       Display display = new Display ();
       Shell shell = new Shell (display);
       Label label = new Label (shell, SWT.CENTER);
       shell.addControlListener (new ControlAdapter () {
          public void controlResized (ControlEvent e) {
             label.setBounds (shell.getClientArea ());
          }
       });

The next snippet uses a layout to achieve the same effect:

       Display display = new Display ();
       Shell shell = new Shell (display);
       Label label = new Label (shell, SWT.CENTER);
       shell.setLayout (new FillLayout ());

Even for this simple example, using a layout reduces the application code. For more complex layouts, the simplification is much greater.

SWT provides four default layout classes that can be used for many situations.