14.10 RowLayout布局
相对于FillLayout来说,RowLayout比较灵活,功能也比较强。用户可以设置布局中子元素的大小、边距、换行及间距等属性。
14.10.1 RowLayout的风格
RowLayout中可以以相关的属性设定布局的风格,用户可以通过“RowLayout.属性”的方式设置RowLayout的布局风格,RowLayout中常用的属性如下。
l Wrap:表示子组件是否可以换行(true为可换行)。
l Pack:表示子组件是否为保持原有大小(true为保持原有大小)。
l Justify:表示子组件是否根据父组件信息做调整。
l MarginLeft:表示当前组件距离父组件左边距的像素点个数。
l MarginTop:表示当前组件距离父组件上边距的像素点个数。
l MarginRight:表示当前组件距离父组件右边距的像素点个数。
l MarginBottom:表示当前组件距离父组件下边距的像素点个数。
l Spacing:表示子组件之间的间距像素点个数。
另外,RowLayout可以通过RowData设置每个子组件的大小,例如“button.setLayoutData (new RowData(60, 60))”将设置button的大小为(60,60),RowLayout风格如表14-3所示。
表14-3 RowLayout风格
|
初 始 状 态 |
调整大小后的状态 |
|
|
wrap = true pack = true justify = false type = SWT.HORIZONTAL (defaults) |
|
|
|
wrap = false (clips if not enough space) |
|
|
|
pack = false (all widgets are the same size) |
|
|
|
justify = true (widgets are spread across the available space) |
|
|
|
type = SWT.VERTICAL (widgets are arranged vertically in columns) |
|
|
14.10.2 RowLayout布局实例
RowLayout是很常用的布局,而且不太复杂。下面通过实例展示RowLayout的布局效果,代码如例程14-15所示。
例程14-15 RowLayoutExample.java
public class RowLayoutExample {
Display display;
Shell shell;
RowLayoutExample() {
display = new Display();
shell = new Shell(display);
shell.setSize(250, 150);
shell.setText("A RowLayout Example");
//新建RowLayout布局
RowLayout rowLayout = new RowLayout();
//子组件保持原有大小
rowLayout.pack = true;
//子组件可换行
rowLayout.wrap = true;
//根据父组件信息调整位置
rowLayout.justify = true;
//左边距为30像素
rowLayout.marginLeft = 30;
//上边距为30像素
rowLayout.marginTop = 30;
//设定父组件RowLayout布局
shell.setLayout(rowLayout);
final Text t = new Text(shell, SWT.SINGLE | SWT.BORDER);
final Button b = new Button(shell, SWT.BORDER);
final Button b1 = new Button(shell, SWT.BORDER);
//设置子组件大小
b1.setLayoutData(new RowData(60, 60));
b.setText("OK");
b1.setText("Cancel");
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public static void main(String[] argv) {
new RowLayoutExample();
}
}
程序中指定了边距和子组件的间距,以及子组件大小的信息,程序运行效果如图14-6所示。

图14-6 RowLayout布局实例








