首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

SWT/JFace 開發實戰:ViewForm 佈局容器詳解與工具欄整合

     編輯:Java 相關知識

前言

org.eclipse.swt.custom.ViewForm 是 SWT 中一個功能強大的佈局容器,繼承自 Composite,專門用於管理頂部、底部、左側、右側及中心區域的控件佈局。本文通過完整代碼示例,演示如何使用 ViewForm 構建帶工具欄的表格界面。

一、基礎示例:創建簡單 ViewForm

package swt_jface.demo9;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class ViewFormExample {
    Display display = new Display();
    Shell shell = new Shell(display);

    public ViewFormExample() {
        shell.setLayout(new FillLayout());

        final ViewForm viewForm = new ViewForm(shell, SWT.BORDER);
        Label label = new Label(viewForm, SWT.NONE);
        label.setText("Top center");

        viewForm.setTopCenter(label); // 設置頂部居中區域
        shell.setSize(400, 200);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) display.sleep();
        }
        display.dispose();
    }

    public static void main(String[] args) {
        new ViewFormExample();
    }
}

關鍵點:ViewForm 提供 setTopLeft、setTopCenter、setTopRight、setBottomLeft、setBottomCenter、setBottomRight、setLeftTop、setLeftCenter、setLeftBottom、setRightTop、setRightCenter、setRightBottom 以及 setContent 等方法,靈活控制各區域控件。

二、進階應用:整合工具欄與 TableViewer

在實際開發中,常需在表格上方放置工具欄。將原本直接建立在 Shell 上的 TableViewer 改為建立在 ViewForm 內,並將工具欄置於頂部左側。

shell.setLayout(new FillLayout());
ViewForm viewForm = new ViewForm(shell, SWT.NONE);
viewForm.setLayout(new FillLayout());

// 1. 創建 TableViewer,父容器改為 viewForm
final TableViewer tv = new TableViewer(viewForm, SWT.BORDER | SWT.FULL_SELECTION);
// ... 省略 TableViewer 列設置、數據綁定代碼 ...

// 2. 創建工具欄
ToolBar toolBar = new ToolBar(viewForm, SWT.FLAT);
ToolBarManager toolBarManager = new ToolBarManager(toolBar);
actionGroup.fillActionToolBars(toolBarManager); // 將 Action 注入工具欄

// 3. 設置佈局:中心區域放表格,頂部左側放工具欄
viewForm.setContent(tv.getControl());    // 主體內容
viewForm.setTopLeft(toolBar);            // 頂部工具欄

shell.open();

ViewForm 佈局示意圖

三、常用佈局策略總結

區域設置方法適用場景
setContent(Control)中心主內容區域(表格、樹、編輯器等)
setTopLeft/TopCenter/TopRight頂部工具欄、標題、搜索框
setBottomLeft/BottomCenter/BottomRight狀態欄、分頁導航、按鈕組
setLeftTop/LeftCenter/LeftBottom左側導航樹、過濾面板
setRightTop/RightCenter/RightBottom右側屬性面板、預覽區

四、最佳實踐建議

  • ViewForm 本身不處理子控件佈局,需為其設置 FillLayout 或 GridLayout。
  • 工具欄建議使用 JFace 的 ToolBarManager 管理 Action,解耦業務邏輯。
  • 動態切換視圖時,調用 setContent(newControl) 並配合 layout() 刷新。
  • 邊框樣式 SWT.BORDER 可視需求開啟。

ViewForm 以其清晰的區域劃分,極大簡化了複雜界面的佈局代碼,是 SWT/JFace 開發中不可或缺的容器組件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved