Understanding layouts in swt
Sponsored Links
This presentation is the property of its rightful owner.
1 / 70

Understanding Layouts in SWT PowerPoint PPT Presentation

  • Uploaded on
  • Presentation posted in: General

Understanding Layouts in SWT. Summary. When writing applications in SWT, you may need to use layouts to give your windows a specific look. A layout controls the position and size of children in a Composite . Layout classes are subclasses of the abstract class Layout .

Download Presentation

Understanding Layouts in SWT

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

Understanding Layouts in SWT


  • When writing applications in SWT, you may need to use layouts to give your windows a specific look.

  • A layout controls the position and size of children in a Composite.

  • Layout classes are subclasses of the abstract class Layout.

  • How to work with standard layouts, and

  • How to writeyour own custom layout class.


  • Positioning and sizing widgets in a parent control does not happen automatically.

  • Two approaches:

    • size and place a Composite’s children initially, or in a resize listener.

    • specify a layout class to position and size the children.

  • Note:If children are not given a size, they will have zero size and they cannot be seen.

Basic Layout Terminology in SWT

Basic Layout Terminology in SWT

  • Composite (in this case, a TabFolder) has a location(x,y), clientArea(x,y, width, height) andtrim.

  • The size of the Composite is the size of the clientArea plus the size of thetrim.

  • This Composite has two children that are laid out side by side.

  • A Layoutis managing the size and position of the children.

  • This Layout allowsspacing between the children, and a margin between the children and the edges of the Layout.

  • The size of the Layout is the same as the size of the Composite’s clientArea.

Preferred Size of a widget

  • The preferred size of a widget is the minimum size needed to show its content.

  • For Composite, the preferred size is the smallest rectangle that contains all of its children.

    • if children positioned by the application, the Composite computes its own preferred size based on the size and position of the children.

    • If a Composite is using a layout class to position its children, it asks the Layout to compute the size of its clientArea, and then it adds the trims to determine its preferred size.

Standard Layouts

  • FillLayout

    • lays out equal-sized widgets in a single row or column

  • RowLayout

    • lays out widgets in a row/colum or rows/columns, with fill, wrap, and spacing options

  • GridLayout

    • lays out widgets in a grid of a fixed number of columns.

  • FormLayout

    • lays out widgets by creating attachments for each of their sides

  • In package org.eclipse.swt.layout

  • All subcalsses of abstract class Layout

Associate a layout to controls

  • usesetLayout(Layout)

    • Shell shell = new Shell();

    • shell.setLayout(new RowLayout());

  • Layout data

    • contains layout data for a specific child.

    • Called layout data class

    • if {A}Layout is a layout class

    •  {A}Data its layout data class name.

  • A widget’s layout data class is set as follows:

    • Button button =new Button(shell, SWT.PUSH);

    • button.setLayoutData(new RowData(50, 40));


import org.eclipse.swt.*;

import org.eclipse.swt.widgets.*;

import org.eclipse.swt.layout.*; 

publicclass LayoutExample { 

publicstaticvoid main(String[] args) {

// main thread is the UI thread

Display display = new Display();

Shell shell = new Shell(display);

// Create the layout.

RowLayout layout = new RowLayout();

// Optionally set layout fields.

layout.wrap = true;

// Set the layout into the composite.


// Create the children of the composite.

new Button(shell, SWT.PUSH)


new Button(shell, SWT.PUSH)

.setText("Wide Button 2");

new Button(shell,SWT.PUSH)

.setText("Button 3");



while (!shell.isDisposed()) {

if (!display.readAndDispatch()) display.sleep();



  • Running the above code results in the following:

  • If resizes s.t. no room for Button 3 on the right

    • =>the RowLayout wraps Button 3 to the next row, as follows:


  • the simplest layout class.

  • lay out widgets in a single row or column, forcing them to have the same width and height.

    • All widgets will share the allocated space except those for margins and spacing.

  • FillLayoutdoes not wrap, but you can specify margins and spacing (default = 0).

    • lay out buttons in a task bar or tool bar,

    • stack checkboxes in a Group.

    • Single child Composite.

      • Ex: if a Shell has a single Group child, FillLayout will cause the Group to completely fill the Shell.

    • no layout data for child elements


FillLayout fillLayout = new FillLayout();

fillLayout.type = SWT.VERTICAL;


   new Button(shell, SWT.PUSH).setText("B1");

new Button(shell, SWT.PUSH).setText("Wide Button 2");

new Button(shell, SWT.PUSH).setText("Button 3");

Margin and Spacing

  • marginWidth, marginHeight, and spacing

    • These fields control the number of pixels between widgets (spacing) and the number of pixels between a widget and the side of the parent Composite (marginWidth and marginHeight).

    • By default, All values are 0.






FillLayout Summary


  • more commonly used than FillLayout

    • can wrap,

    • configurable margins and spacing.

  • has a number of configuration fields.

  • the height and width of each widget in a RowLayout can be specified by setting the widget’s RowData object using setLayoutData.

RowLayout Configuration Fields

  • type [=SWT.HORIZONTAL] // 水平/垂直分布

    • controls whether the contained widgets are layouted in horizontal rows, or vertical columns.

  • Wrap [=true] ; // 捲折

    • controls whether the row of widgets may be wrapped into the next row if there isn’t enough space.

  • Pack [=true]// 相同/不等 寬高

    • If true, widgets take their preferred size(from RowData or computeSize() ), and be aligned to the left.

    • If false, all widgets will get an equal size (for width as well as height), which is the maximum of the preferred sizes of all children; somewhat different from FillLayout.

  • justify [=false]// 額外空白 由連接區均分 / 置於後端

    • true  extra space than needed distributed evenly among margins/spacings b/t widgets.

    • false  extra space left at the right/bottom end.

    • Note: While pack and fill will affect the size of child widgets, justify does not.

The fill field in a RowLayout

  • fill [= false] // 同列(欄)是否等高(寬)

    • Indicates whether all controls in a row (or column) will have the same height (or width).

      • same height (or width) => select the largest control in the row( or column).

    • fill=false

      • for controls in a row with different height  Even on top and ragged on bottom. (top aligned )

      • for controls in a column with different width  Even on left and ragged on right. (left aligned )

      • fill = true  even on both sides.

Margin and Spacing

  • marginHeigth, marginWidth, spacing:

    • same as FillLayout

  • marginLeft, marginTop, marginRight, marginBottom

    • These fields specify additional number of pixels between a widget and the side of the parent Composite (margin).

    • By default, RowLayouts leave 3 pixels for margins and spacing.

RowLayout Examples

  • RowLayout rowLayout = new RowLayout();

  • rowLayout.wrap = false;   rowLayout.pack = false;

  • rowLayout.justify = true;

  • rowLayout.type = SWT.VERTICAL;

  • rowLayout.marginLeft = 5;   rowLayout.marginTop = 5;

  • rowLayout.marginRight = 5;  rowLayout.marginBottom = 5;

  • rowLayout.spacing = 0;

  • shell.setLayout(rowLayout);

  • If Using default layout => only line 1. Is needed.


Using RowData Objects with RowLayout

publicclass RowDataExample { 

publicstaticvoid main(String[] args) {

       Display display = new Display();

       Shell shell = new Shell(display);

       shell.setLayout(new RowLayout());

       Button button1 = new Button(shell, SWT.PUSH);

       button1.setText("Button 1");

       button1.setLayoutData(new RowData(50, 40));

       Button button2 = new Button(shell, SWT.PUSH);

       button2.setText("Button 2");

       button2.setLayoutData(new RowData(50, 30));

Button button3 = new Button(shell, SWT.PUSH);

    button3.setText("Button 3");

    button3.setLayoutData(new RowData(50, 20));



while (!shell.isDisposed()) {

if (!display.readAndDispatch()) display.sleep();




  • the most useful and popularly used

  • the widget children of a Composite are laid out in a grid.

  • has a number of configuration fields,

  • Each widget can have an associated layout data, called GridData.

    • The power of GridLayout lies in the ability to configure GridData for each widget .

GridLayout Configuration Fields

  • numColumns [=1]

    • Number of columns in a row

    • If #widgets > numColumns => wrap into next rows.


Display display = new Display();

Shell shell = new Shell(display);

GridLayout gridLayout = new GridLayout();

gridLayout.numColumns = 3;


new Button(shell, SWT.PUSH).setText("B1");

new Button(shell, SWT.PUSH).setText("Wide Button 2");

new Button(shell, SWT.PUSH).setText("Button 3");

new Button(shell, SWT.PUSH).setText("B4");

new Button(shell, SWT.PUSH).setText("Button 5");

shell.pack();   shell.open();

while (!shell.isDisposed()) {

if (!display.readAndDispatch()) display.sleep();   }

  • makeColumnsEqualWidth [=false]

    • forces all columns to be the same width.

    • (note that in the absence of further instruction, widgets are left-justified in their columns).

    • by default the width of a column is the width of the widest widget in the column.


  • marginWidth, marginHeight, horizontalSpacing, andverticalSpacing

  • similar to those in a RowLayout.

    • left and right margins are grouped into marginWidth,

    • the top and bottom margins are grouped into marginHeight.

    • can specify horizontalSpacing and verticalSpacing independently,

      • whereas in a RowLayout, spacing applies to horizontal or vertical depending on the type of the RowLayout.

GridData Object Fields

  • GridData

    • the layout data object associated with GridLayout.

    • use setLayoutData method to set a widget’s GridData object.

    • note: Do not share GridData: each widget must have its own GridData.

  • Example:

    Button button1 = new Button(shell, SWT.PUSH);


    // all gridData fields are set to default values

       button1.setLayoutData(new GridData());

How to set GridData Fields

1. Set the fields directly, like this: 

GridData gridData = new GridData();

gridData.horizontalAlignment = GridData.FILL;

gridData.grabExcessHorizontalSpace = true;


 2. Use style bits defined in GridData:

button1.setLayoutData( new GridData(


GridData.GRAB_HORIZONTAL));// or further

button1.setLayoutData(new GridData(


HorizontalAlignment and VerticalAlignment

  • The alignment fields specify where to place a widget horizontally and/or vertically within its grid cell.

  • Each alignment field can have one of the following values:

    • BEGINNING [置左/置上]

    • CENTER [置中]

    • END [置右/置下]

    • FILL [佈滿空格]

    • defined in both SWT and GridData classes.

  • Default values:

    • horizontalAlignment ==>BEGINNING (or left-aligned).

    • verticalAlignment ==>CENTER.

Example: vary the horizontalAlignment of Button 5.


  • Allows you to move a widget to the right by a specified number of pixels.

  • useful only when the horizontalAlignment is BEGINNING.

  • Ex:

    GridData gridData = new GridData();

    gridData.horizontalIndent = 4;



HorizontalSpan and VerticalSpan

  • The span fields let widgets occupy more than one grid cells.

    • often used in conjunction with FILL alignment.

  • Example: make Button 5 span the last two cells:

    GridData gridData = new GridData();

    gridData.horizontalAlignment = GridData.FILL;

    gridData.horizontalSpan = 2;


More Examlpes

  • make Wide Button 2 span two cells instead:  

    GridData gridData = new GridData();

    gridData.horizontalAlignment = GridData.FILL;

    gridData.horizontalSpan = 2;


  • make Button 3 span two cells vertically:

    GridData gridData = new GridData();

    gridData.verticalAlignment = GridData.FILL;

    gridData.verticalSpan = 2;


GrabExcessHorizontalSpace and GrabExcessVerticalSpace

  • typically used for larger widgets such as Text,List or Canvasto allow them to grow if their containing Composite grows.

    • If a Text is grabbing excess horizontal space and the user resizes the Shell wider, then the Text will get all of the new horizontal space and other widgets in the same row will stay their original width.

    • Of course, the widget that is grabbing excess space is also the first one to shrink when the Shell gets smaller.

    • It is easiest to always think of the grabExcessSpace fields in the context of resizing.


  • original :  after resizing

  • new GridData:

    • B3: grab excess horizontal and

    • vertical space,

    • B1,B4:fill vertically ( w/o

    • grabbing)

The code

Button button1 = new Button(shell, SWT.PUSH);


   GridData gridData = new GridData();

   gridData.verticalAlignment = GridData.FILL;


new Button(shell, SWT.PUSH).setText("Wide Button 2");

   Button button3 = new Button(shell, SWT.PUSH);

   button3.setText("Button 3");

   gridData = new GridData();

   gridData.verticalAlignment = GridData.FILL;

gridData.verticalSpan = 2;

gridData.grabExcessVerticalSpace = true;

gridData.horizontalAlignment = GridData.FILL;

gridData.grabExcessHorizontalSpace = true;


Button button4 = new Button(shell, SWT.PUSH);


   gridData = new GridData();

gridData.verticalAlignment = GridData.FILL;


new Button(shell, SWT.PUSH).setText("Button 5");

  • If more than one widget is trying to grab the same space, then the excess space is shared evenly among the grabbing widgets:

  •  original resize:

Final Notes

  • If a widget is grabbing excess horizontal/vertical space and its parent Composite grows wider/taller

    • then the entire column/row containing that widget grows wider/taller.

  • Implications:

    • if any other widget in the affected column or row has fill alignment, then it will stretch also.

    • Widgets that have beginning, center, or end alignment will not stretch – they will stay at the beginning, center or end of the wider column or taller row.

WidthHint and HeightHint

  • Indicate the number of pixels wide or tall that you would like a widget to be, if it does not conflict with other requirements in the GridLayout’s constraint system.

  • Example:

    • Looking back at the five-button, three-column example, say we want Button 5 to be 70 pixels wide and 40 pixels tall.

    • We code it as follows:

    • GridData gridData = new GridData();

    •        gridData.widthHint = 70;

    •        gridData.heightHint = 40;

    •        button5.setLayoutData(gridData);

public fields of GridData

  • verticalAlignment, horizontalAssignment :

    • Specifies the vertical (horizontal) alignment of the control within a cell.


  • widthHint, heightHint :

    • The amount of space in pixels to be used as the width hint for the control.

    • The default value is SWT.DEFAULT.

  • horizontalIndent [1]

    • specifies the number of pixels of indentation to be placed on the left side of the cell.

  • horizontalSpan, verticalSpan : [1]

    • Specifies the number of columns (rows) that the cell will fill.

  • grabExcessHorizontal, grabExcessVerticalSpace : [false]

    • Indicates that this cell will accept any excess vertical space that remains after each cell has been placed. If more than one instance of GridData wants excess space, it is divided evenly among them.

GridData constructors

  • GridData() = GridData(SWT.DEFAULT, SWT.DEFAULT)

  • GridData(int width, int height)

  • GridData(int horizontalAlignment, int verticalAlignment, boolean grabExcessHorizontalSpace, boolean grabExcessVerticalSpace, int horizontalSpan, int verticalSpan)

  • GridData(int horizontalAlignment, int verticalAlignment, boolean grabExcessHorizontalSpace, boolean grabExcessVerticalSpace)

  • GridData(int stylebits)

    • very general but have to remember many cryptic constants. not recommended.

  • The natural size of Button5 : 70-pixel wide, 40-pixel tall.                

  • Note: if the horizontalAlignment of Button 5 was FILL, then the GridLayout would not have been able to honor the request for a width of 70 pixels.


  • Works by creating FormAttachments for each side of the widget, and storing them in the layout data.

  • An attachment ‘attaches’ a specific side of the widget either to a position in the parent Composite or to another widget within the layout.

  • provides tremendous flexibility when laying out, as it allows you to specify the placement of individual widgets within the layout.

FormLayout Configuration Fields

  • MarginWidth, MarginHeight

    • Similar to GridLauoyt; 0 by default.

    • can also be defined on a per-widget basis in the attachments.

  • Example code:

    Display display = new Display ();

    Shell shell = new Shell (display);

    FormLayout layout= new FormLayout ();

    layout.marginHeight = 5;

    layout.marginWidth = 5;

    shell.setLayout (layout);

FormData Object Fields

  • specify how each widget in a FormLayout will be laid out.

    • Each FormData object defines the attachments for all four sides of the widget. These attachments tell where to position each side of the widget.

  • Example :

    Button button1 = new Button(shell, SWT.PUSH);


       button1.setLayoutData(new FormData());

  • Notes:

    • The default attachments attach the widget to the top and left edges of the parent Composite.

    • all widgets used the default attachments => laid out one on top of another in the top left corner of the parent Composite.


  • A FormAttachmentis used to attach a designated side of the widget to the parent Compositeor another peer widget in the layout. 

    • We typically do not set attachments on all sides of a widget. 

    • It is very common to specify only one horizontal (left or right) attachment and one vertical (top or bottom) attachment and allow the widgets to take the size specified in their FormData, or their preferred size if no size is specified in the FormData.

Configure FormAttachment

  • Attachments can be configured in a variety of ways:

  • attach to a position (percentage value 0-100) in the parent widget. 

  • attach to the adjacent side of a target widget inside the composite. [+ optional pixel offset ].  

  • attach to the opposite side of a target widget inside the composite.  An optional pixel offset can be added. 

    • can be used to align the top of a widget with the top of another widget so that they will always line up vertically.

  • center the widget relative to a target widget.

    • need only be specified for one side (left or right, top or bottom) in the direction being centered.

Attributes of FormLayout and FormData

  • FormLayout:

    • marginHeight :

    • marginWidth:

  • FormData:

    • top : the FormAttachment for the top side of the

    • control.

    • left : the FormAttachment for the left side of the control.

    • bottom :

    • right:

    • width : the preferred width in pixels.

    • height:

Attributes of FormAttachments

  • alignment:

    • Specifies the alignment of the control side that is attached to a control. 

    • DEFAULT =>attach to the adjacent side of the specified control. 

    • top/bottom attachments => TOP, BOTTOM, or CENTER

    • left/right attachments=> LEFT, RIGHT, and CENTER.

  • control:

    • the control to which the widget is attached.

  • denominator(d [=100] ), numerator(n):

  • offset(o [=0]):

  • Note: actual attaching position of the widget= (n/d) * x + o.

Example 1: Attaching to a Position of parent control

  • Ex: attach the top of widget to the top of parent control at position: 20% + 10pixels.  

    FormData formData = new FormData();

    // 50 % + 0 offset of parent control or Form…(10,20, 0)

    formData.top = new FormAttachment(50,0);


Attaching the right side to the right side of Parent control

  • FormData formData = new FormData();

  • formData.right = new FormAttachment(100,-5);

  • button1.setLayoutData(formData);

Attaching to peer Widget

FormData formData = new FormData();

      formData.top = new FormAttachment(20,0);


      FormData formData2 = new FormData();

formData2.top = new FormAttachment(button1,10);


10 pixels

10 pixels

FormData formData = new FormData(50,50);

formData.top = new FormAttachment(20,0);


FormData formData2 = new FormData();

FormData2.left = new FormAttachment(button1,5);

formData2.top = new FormAttachment(button1,0,SWT.TOP);


20/100 x + 0


FormData formData1 = new FormData (50,50);


FormData formData2 = new FormData ();

formData2.left = new FormAttachment (button1,5);

formData2.top = new FormAttachment (button1,0,SWT.CENTER);

// equ.to.

// formData2.bottom = new FormAttachment (button1,0,SWT.CENTER);

button2.setLayoutData (formData2);

A FormLayout Example

FormData data1 = new FormData();

data1.left = new FormAttachment(0,5);

data1.right = new FormAttachment(25,0);


FormData data2 = new FormData();

data2.left = new FormAttachment(button1,5);

data2.right = new FormAttachment(100,-5);


FormData data3 = new FormData(60,60);

data3.top = new FormAttachment(button1,5);

data3.left = new FormAttachment(50,-30);

data3.right = new FormAttachment(50,30);


FormData data4 = new FormData();

data4.top = new FormAttachment(button3,5);

data4.bottom = new FormAttachment(100,-5);

data4.left = new FormAttachment(25,0);


FormData data5 = new FormData();

data5.bottom = new FormAttachment(100,-5);

data5.left = new FormAttachment(button4,5);


The result


  • Like CardLayout in AWT/SWing

  • creates a conceptual stack of widgets.

    • All widgets set to have the same size and location, and the one that is designated as topControl is shown.

    • Users must set the topControl value to flip between the visible items and then call layout() on the composite which has the StackLayout.

  • Fields:

    • marginWdith, marginHeight,

    • topControl.


Display display = new Display(); Shell shell = new Shell(display);

final StackLayout layout = new StackLayout();


final Button[] bArray = new Button[10];

for (int i = 0; i < 10; i++) {

bArray[i] = new Button(parent, SWT.PUSH);

bArray[i].setText("Button "+i); }

layout.topControl = bArray[0];

Button b = new Button(shell, SWT.PUSH);

b.setText("Show Next Button");

final int[] index = new int[1];

b.addListener(SWT.Selection, new Listener(){

public void handleEvent(Event e) {

index[0] = (index[0] + 1) % 10;

layout.topControl = bArray[index[0]];

parent.layout(); } } ); shell.open(); … }

  • Login