Eclipse Forms 是 Eclipse 3.0 引入的 UI 工具包,原為 PDE/Update 內部使用,3.0 起開放為公共 API。它提供**類 Web 表單體驗**的 SWT 介面:可滾動表單、超鏈接、圖片鏈接、表格佈局、扁平化邊框等。本文基於官方指南,實作入門三步驟。
getBody() 返回內容 Composite。public class FormView extends ViewPart {
private FormToolkit toolkit;
private ScrolledForm form;
public void createPartControl(Composite parent) {
toolkit = new FormToolkit(parent.getDisplay());
form = toolkit.createScrolledForm(parent);
form.setText("Hello, Eclipse Forms"); // 標題欄文字
}
public void setFocus() { form.setFocus(); }
public void dispose() {
toolkit.dispose(); // 釋放色彩、字體、圖片資源
super.dispose();
}
}
plugin.xml 註冊視圖與依賴:
<requires>
<import plugin="org.eclipse.ui.forms"/>
</requires>
<extension point="org.eclipse.ui.views">
<view class="org.xqtu.samples.views.FormView" name="Form Sample" id="FormView"/>
</extension>
Composite body = form.getBody();
GridLayout layout = new GridLayout();
body.setLayout(layout);
Hyperlink link = toolkit.createHyperlink(body, "Click here.", SWT.WRAP);
link.addHyperlinkListener(new HyperlinkAdapter() {
public void linkActivated(HyperlinkEvent e) {
System.out.println("Link activated!");
}
});
layout.numColumns = 2;
GridData gd = new GridData();
gd.horizontalSpan = 2;
link.setLayoutData(gd);
Label label = toolkit.createLabel(body, "Text field label:");
Text text = toolkit.createText(body, "");
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// 關鍵:設置扁平邊框渲染提示
text.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
Button button = toolkit.createButton(body,
"An example of a checkbox in a form", SWT.CHECK);
gd = new GridData();
gd.horizontalSpan = 2;
button.setLayoutData(gd);
// 統一重繪邊框,實現扁平化外觀
toolkit.paintBordersFor(body);
| 模式 | Forms 體現 |
|---|---|
| 工廠模式 | FormToolkit 集中創建、配置、資源管理 |
| 適配器模式 | HyperlinkAdapter 簡化事件監聽 |
| 佈局委託 | TableWrapLayout 模擬 HTML 表格行列跨越 |
toolkit.dispose()** → 色彩/字體/圖片資源洩漏,長期運行導致 UI 異常。new Text()) → 外觀與 Forms 風格不一致(3D vs 扁平),事件處理差異。paintBordersFor() → Text/Combo 等控件無扁平邊框效果。「Eclipse Forms 讓 SWT 擁有類 Web 的表單開發體驗,配合 Toolkit 統一風格,是構建豐富 Eclipse RCP 應用的利器。」