Layouts

Often the best way to handle simple widget positioning is in a resize event listener. 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.

There are some general definitions used when resizing and positioning widgets:

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:

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.

The following table summarizes the standard layouts provided by SWT.

Layout
Purpose
FillLayout Lays out controls in a single row or column, forcing them to be the same size.
FormLayout Positions the children by using FormAttachments to optionally configure the left, top, right and bottom edges of each child.
GridLayout Positions the children by rows and columns.
RowLayout Places the children either in horizontal rows or vertical columns.