當標準對話框對於您的外掛程式來說太簡單時,您可以使用 Dialog 類別建置自己的對話框。先前我們看到 Readme 工具如何在動作集中提供「開 啟 Readme 瀏覽器」動作。這個動作集顯示在工作台工具列和 Window->Readme 檔編輯器功能表。
現在我們準備在 Readme 工具的 WindowActionDelegate 中瞭解這個動作的實作。
public void run(IAction action) { SectionsDialog dialog = new SectionsDialog(window.getShell(), ReadmeModelFactory.getInstance().getSections(selection)); dialog.open(); }
動作集的視窗動作委派使用資源導覽器視圖中的現行選擇(.readme 檔)取得 Readme 檔中的區段清單。 這個清單和工作台視窗的 Shell 會傳遞到 SectionsDialog。
使用者選取動作時會開啟 SectionsDialog。
SectionsDialog 是在 Readme 工具外掛程式中實作,其方法是在 org.eclipse.jface.dialogs 套件中繼承 Dialog 類別。
Dialog 類別為建置對話框 Shell 視窗、建立一般對話框按鈕和啟動對話框提供基本支援。 子類別負責處理對話框本身的內容:
SectionsDialog 建立 SWT 清單以顯示區段清單。 它使用 JFace 檢視器移入清單。 (我們將在 檢視器中瞭解 JFace 檢視器。) 請注意:我們的對話框不必建立對話框的任何按鈕,因為我們的 Super 類別會執行這個動 作。
protected Control createDialogArea(Composite parent) { Composite composite = (Composite)super.createDialogArea(parent); List list = new List(composite, SWT.BORDER); ... ListViewer viewer = new ListViewer(list); ... return composite; }
protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(MessageUtil.getString("Readme Sections")); ... }
對話框可以隨需要而變得簡單或複雜。 實作對話框時,大部分對話框程式碼與建立代表其內容區的 SWT 控制項相關,並在 對話框開啟時處理必要的事件。 使用者按下按鈕之後,對話框可以查詢組成對話框的各種控制項(或檢視器)的 狀態以決定下一步。
在某些情況下,您可能會想在對話框中顯示某些東西的相關資訊,不過,您只想用比一般對話框「小型」的方式。 例如,預期對話框只提供暫時性資訊,很容易跳出,使用者工作的焦點不需要移到這個對話框。 若是如此,您可以利用 PopupDialog 類別來實作這個對話框。 在若干方面上,PopupDialog 的外觀和操作方式不同於一般 Dialog。 它底端沒有任何按鈕,也沒有標準視窗標題列,它的邊框、間距和字體都較小而精簡。
雖然 PopupDialog 看起來與一般對話框很不同,但外掛程式子類別中定義對話框內容的程式碼幾乎完全相同。 您仍是實作 createDialogArea 方法來建立這個對話框的 SWT 控制項。 應用程式碼的主要差異在於建立這個對話框的建構子,它的參數比一般 Dialog 類別還多。 例如,只要變更對話框的超類別,並在建構子中配置對話框,SectionsDialog 就可以轉換成 PopupDialog:
public class SectionsDialog extends PopupDialog { protected IAdaptable input; /** * Creates a new SectionsDialog. */ public SectionsDialog(Shell parentShell, IAdaptable input) { super(parentShell, SWT.DEFAULT, false, // do not take focus when opened false, // do not persist the bounds false, // do not show a resize menu false, // do not show a menu item for persisting bounds null, // no title null); // no info text this.input = input; } ...