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:
- 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.
- The clientArea is the area in which a child can be placed without
being clipped.
- 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.
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. |