4、定义向导
(1)向导概述
l JFace工具箱支持向导这种特殊控件,以提供一种灵活的机制,收集用户的输入信息,并进行输入验证
l 本教程中创建一个JFace向导,用来收集Google搜索使用的License Key,在前面讲到的SerachView视图中会使用收集的License Key
search.setKey(LicenseKeyWizard.getLicenseKey());
(2)创建LicenseKeyWizard类
package com.xqtu.google.wizards;
import org.eclipse.jface.wizard.Wizard;
public class LicenseKeyWizard extends Wizard {
private static String licenseKey;
private LicenseKeyWizardPage page;
public LicenseKeyWizard() {
super();
this.setWindowTitle("License Key");
}
public boolean performFinish() {
if(page.getLicenseKeyText().getText().equalsIgnoreCase(""))
{
page.setErrorMessage("You must provide a license key.");
page.setPageComplete(false);
return false;
}
else
{
licenseKey = page.getLicenseKeyText().getText();
return true;
}
}
public void addPages() {
page = new LicenseKeyWizardPage("licenseKey");
addPage(page);
}
public static String getLicenseKey() {
return licenseKey;
}
public static void setLicenseKey(String licenseKey) {
LicenseKeyWizard.licenseKey = licenseKey;
}
}
l LicenseKeyWizard向导类扩展Wizard类(实现IWizard接口的抽象基类),需要实现addPages和performFinish方法,前者将向导页对象加到向导中,后者在用户点击Finish按钮时执行,完成具体功能
l LicenseKeyWizard类定义了static的属性licenseKey,用来保存收集的License Key
l addPages方法比较简单,创建LicenseKeyWizardPage(后面介绍)对象,加到向导中
l performFinish方法先对LicenseKeyWizardPage中提供的文本域内容进行数据有效性验证,如果数据无效,提示错误信息,否则保存到licenseKey属性中
(3)创建LicenseKeyWizardPage类
package com.xqtu.google.wizards;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
public class LicenseKeyWizardPage extends WizardPage {
private Text licenseKeyText;
protected LicenseKeyWizardPage(String pageName) {
super(pageName);
setTitle("License Key");
setDescription("Define your Google API License Key");
}
public void createControl(Composite parent) {
GridLayout pageLayout = new GridLayout();
pageLayout.numColumns = 2;
parent.setLayout(pageLayout);
parent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label label = new Label(parent, SWT.NONE);
label.setText("License Key:");
licenseKeyText = new Text(parent, SWT.BORDER);
licenseKeyText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
setControl(parent);
}
public Text getLicenseKeyText() {
return licenseKeyText;
}
public void setLicenseKeyText(Text licenseKeyText) {
this.licenseKeyText = licenseKeyText;
}
}
l 向导页面类扩展WizardPage类(实现IWizardPage接口的抽象基类),需要实现createControl方法来创建中的控件;本教程的向导只有一个向导页面LicenseKeyWizardPage
l 在构造方法中设置了向导页面的标题和描述;在createControl方法中创建了License Key标签和对应的文本域(方法同视图)