Attaching a Layout to a Container

The first step in using the layout that you have chosen is to attach that layout to a container class (one of the classes that contains other widgets such as Shell, Composite, or Group).

How do I do that?

No matter which layout you choose to use, the same two steps are required to attach it to a container:

  1. Create an instance of the layout class you wish to use (i.e., FillLayout).

  2. Call the setLayout() method on the container instance to attach the layout.

Example 9-1 creates an instance of FillLayout and attaches it to a Shell .

Example 9-1. Using FillLayout

import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

public class LayoutExample {
    Display d;
    Shell s;
    LayoutExample( )    {
        d = new Display( );
        s = new Shell(d);
        s.setSize(500,500);
        s.setImage(new Image(d, "c:\\icons\\JavaCup.ico"));
        s.setText("A Shell Menu Example");
        s.setLayout(new FillLayout( ));
        s.open( );
        while(!s.isDisposed( )){
            if(!d.readAndDispatch( ))
                d.sleep( );
        }
        d.dispose( );
    }
}

The shell in this example is now configured to use FillLayout. Widgets added to the shell will be positioned and sized according to the rules governing FillLayout, with no further programming required to control their position or size.

Get SWT: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.