1 布局方式
布局名称 |
特点说明 |
适合场景 |
AbsoluteLayout |
绝对定位,控件位置和大小完全由开发者手动设置。 |
特殊定制界面、不规则排版 |
FillLayout |
简单线性布局,将所有子控件填满容器(水平或垂直方向)。 |
快速原型、内容较少时 |
GridLayout |
网格布局,类似 HTML 表格,支持跨行、跨列,最常用布局之一。 |
表单布局、复杂对齐界面 |
FormLayout |
使用边界或参考对齐方式,子控件通过 FormData 与容器或其他控件关联。 |
精细控件对齐、精确控制布局位置 |
RowLayout |
行布局,控件水平或垂直排列,自动换行,不支持跨行跨列。 |
简单水平按钮组或列表 |
StackLayout |
堆叠布局,只显示一个子控件(如卡片式 UI)。 |
选项卡、向导式页面切换 |
BoxLayout |
Swing 专属,不是 SWT 的标准布局。可能是 SWT Designer 的扩展。 |
与 Swing 混合使用(一般不用) |
FlowLayout |
Swing 布局,不是 SWT 原生布局,控件顺序排列并自动换行。 |
Swing 风格界面(SWT 中不常用) |
BorderLayout |
Swing 的经典布局:北/南/东/西/中,SWT 中不是原生,有些第三方扩展中提供。 |
移植 Swing 程序时使用 |
2 测试代码
package com.xu.gui;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
public class TestGui {
protected Shell shell;
public static void main(String[] args) {
try {
TestGui window = new TestGui();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
protected void createContents() {
shell = new Shell();
shell.setSize(582, 434);
shell.setText("SWT Application");
shell.setLayout(new FillLayout(SWT.HORIZONTAL));
Composite composite = new Composite(shell, SWT.NONE);
composite.setLayout(new FormLayout());
ProgressBar bar = new ProgressBar(composite, SWT.NONE);
bar.setToolTipText("进度条");
bar.setMinimum(0);
bar.setMaximum(100);
FormData barData = new FormData();
barData.left = new FormAttachment(0, 0);
barData.right = new FormAttachment(100, 0);
barData.top = new FormAttachment(0, 0);
barData.height = 20;
bar.setLayoutData(barData);
Button button = new Button(composite, SWT.NONE);
button.setText("进度条");
FormData buttonData = new FormData();
buttonData.left = new FormAttachment(0, 10);
buttonData.bottom = new FormAttachment(100, -10);
button.setLayoutData(buttonData);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
progress(bar);
}
});
}
private void progress(ProgressBar bar) {
bar.setSelection(0);
Display.getDefault().asyncExec(() -> {
for (int i = 0; i <= 100; i++) {
bar.setSelection(i);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
