Eclipse

     

Selecting a layout lets you specify how to arrange your controls; there are four layout classes built into SWT:

FillLayout

Lets you fill a shell's client area.

GridLayout

Lays out control children in a grid.

RowLayout

Lays out controls in either horizontal rows or vertical columns .

FormLayout

Lets you position controls relative to the parent composite or another control. It is the most precise of all the layouts.

For example, here's how the grid layout works. We're going to create a grid layout with four columns and fill it with buttons . In this case, we'll create a new Composite control, which can contain other controls, and fill the composite with buttons. To start, we create a new shell and use a row layout to display our composite control. Then we create the composite control and a grid layout in it with four columns (the SWT.NONE constant means we're not setting any nondefault styles here):

public static void main (String [] args) { Display display = new Display ( ); final Shell shell = new Shell (display); shell.setSize(300, 200); shell.setLayout(new RowLayout( )); final Composite composite = new Composite(shell, SWT.NONE); GridLayout gridLayout = new GridLayout( ); gridLayout.numColumns = 4; composite.setLayout(gridLayout); . . .

All that's left is to add the buttons to the composite control using a loop and to add the event loop itself, as you see in Example 7-3.

Example 7-3. Using SWT layouts, Ch07_03.java

package org.eclipsebook.ch07; import org.eclipse.swt.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; public class Ch07_03 { public static void main (String [] args) { Display display = new Display ( ); final Shell shell = new Shell (display); shell.setSize(300, 200); shell.setLayout(new GridLayout( )); final Composite composite = new Composite(shell, SWT.NONE); GridLayout gridLayout = new GridLayout( ); gridLayout.numColumns = 4; composite.setLayout(gridLayout); for (int loopIndex = 0; loopIndex < 18; loopIndex++) { Button button = new Button(composite, SWT.PUSH); button.setText("Button " + loopIndex); } shell.open ( ); while (!shell.isDisposed( )) { if (!display.readAndDispatch( )) display.sleep( ); } display.dispose ( ); } }

You can see the results in Figure 7-3, where we've arranged our buttons using a grid layout.

Figure 7-3. Using a grid layout

The form layout is relatively new and very powerful because it allows you to position controls where you want them relative to other controls or the container.

Категории