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:
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.
SWT provides four default layout classes that can be used for many situations.