Java Tutorial/SWT/Layout Basics
Содержание
A few terms that are used frequently when discussing layouts
- Client area: the size of the composite"s bounds minus its trim.
- Margins: the number of pixels placed on an edge of the layout.
- Spacing: the number of pixels between the edges of children of a composite.
- Preferred size: best-display size.
Laying Out Children of a Composite
public void layout(boolean changed)
Layouts
A layout can be used to control the position and size of children of a composite. Four standard layouts and one custom layout provided in SWT:
- FillLayout
- RowLayout
- GridLayout
- FormLayout
- StackLayout
Layout term: bounds, client area
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class LayoutTerm {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
System.out.println("Bounds: " + shell.getBounds());
System.out.println("Client area: " + shell.getClientArea());
shell.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
RowLayout rowLayout = new RowLayout();
shell.setLayout(rowLayout);
Button button1 = new Button(shell, SWT.PUSH);
button1.setText("button1");
Button button2 = new Button(shell, SWT.PUSH);
button2.setText("button2");
Button button3 = new Button(shell, SWT.PUSH);
button3.setText("button33333333333333333333333333333333333333");
shell.pack();
shell.open();
System.out.println("button1: " + button1.getBounds());
System.out.println("button2: " + button2.getBounds());
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
Setting Layouts
public Layout getLayout()
public void setLayout(Layout layout)
By default, a composite does not have any layout.
Using Layout Data Objects to control layout
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class LayoutDataControlLayout {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout()); // Only with GridLayout you can use GridData
Text text = new Text(shell, SWT.SINGLE|SWT.BORDER);
text.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL));
shell.setSize(450, 100);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}