使用Eclipse向导进行快速开发插件.doc_第1页
使用Eclipse向导进行快速开发插件.doc_第2页
使用Eclipse向导进行快速开发插件.doc_第3页
使用Eclipse向导进行快速开发插件.doc_第4页
使用Eclipse向导进行快速开发插件.doc_第5页
免费预览已结束,剩余21页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

使用Eclipse向导进行快速开发插件入门 本文将演示如何使用向导把新文件添加到已有 Eclipse 项目中。当内置模板功能不足时,Eclipse 向导是定义可重复文件类型模板的优秀方法。阅读完本文后,您应当能够在 Eclipse 中实现自己的向导以创建新文件。为了发挥本文的最大功效,您必须熟悉如何构建 Java 编程语言类,并且还应当熟悉继承和使用接口。您应当能够启动 Eclipse,但是本文假定您并不精通 Eclipse。Eclipse 向导概览我喜欢 Eclipse IDE 的很多特性。其中之一就是可扩展性。通过添加提供功能的插件(包括自动创建类、接口、项目、其他资源的向导),可以轻松地自定义 IDE。此特性对于大型企业来说非常重要,在这类企业中可以基于 Eclipse IDE 流线化地构建和分发插件,使许多人都可以自动利用功能。在任何企业中,让团队以相同的样式构建应用程序可以提供许多优点。如果应用程序是以一致的样式构建的,则应用程序将更易于维护。一致性可以帮助减少错误。此外,由于应用程序是以相同的样式构建的,因此团队成员可以更轻松地完成一个又一个项目。能够为 Eclipse 框架创建自定义向导使企业可以构建企业专有的向导,这些向导将给团队提供使用一致的最佳实践创建应用程序的机会。创建新向导本文中构建的自定义向导位于 Eclipse 的插件项目中。开始创建自定义向导十分简单,这要感谢为您开始编写代码提供前期帮助的其他向导。在接下来的步骤中,将使用 Plug-in Project 向导创建插件的开头部分。要构建新插件项目,请执行以下步骤:选择 File New Project 以选择项目向导。在 Plug-in Development 下选择 Plug-in Project,如下所示:单击 Next 前进到下一步。图 1. 选择插件项目添加项目名称(在本文中,该名称为 ExampleWizard(不是那么有创造性),如图 2 所示)。如果没有特殊原因,请使用默认位置。单击 Next。图 2. 新插件项目在 Plug-in Version 中输入版本号,并添加插件名称和插件提供者的名称(可能是您,也可能是协作的团队)。请一定要更新 Activator 的包名称,它默认为小写版本的项目名称。最好使用符合您公司标准的包名称:例如 com.example.eclipse.wizards。当您填写完下图中所示的信息后,单击 Next。图 3. 选择插件项目选择 Custom plug-in wizard,因为使用此选项可以让您对所包括的组件进行微调。如果您以前从未创建过新插件项目,那么现在最好看看其他模板的描述以了解可用信息。单击 Next。在 Template Selection 窗口中,单击 Deselect All 取消选中所有选项。然后,选择 New File Wizard,如下所示。单击 Next。图 4. 选择模板Eclipse 向导将给您提示一些关于正在创建的新向导的信息(参见图 5)。确保更新包名称,理想情况下将其更新为 Activator 所使用的相同名称 (com.example.eclipse.wizards)。将 Wizard Category Name 更新为新向导文件夹的名称。该值的使用方法与 图 1 中的 Plug-in Development 类别相同。Wizard Class Name 是从 Wizard 继承的类的 Java 类名,该类将实现 INewWizard 接口。Wizard Page Class Name 将扩展 WizardPage 类。图 5. New Wizard Options 窗口单击 Finish。Eclipse 将给新项目添加必要的类和库。虽然还没完成,但是已经有了很好的开端并且准备好开始在向导背后添加一些实现。Wizard 类和 INewWizard 接口现在项目中有三个类:NewXHTMLFileWizard、NewXHTMLFileWizardPage 和 Activator。下面的部分将处理 NewXHTMLFileWizard 类。该类如清单 1 所示,不过没有显示方法中的所有代码。清单 1. NewXHTMLFileWizard 类public class NewXHTMLFileWizard extends Wizard implements INewWizard private NewXHTMLFileWizardPage page;private ISelection selection;public NewXHTMLFileWizard() / snipped.public void addPages() / snipped.public boolean performFinish() / snipped.private void doFinish(/ snipped.private InputStream openContentStream() / snipped.private void throwCoreException(String message) throws CoreException / snipped.public void init(IWorkbench workbench, IStructuredSelection selection) / snipped.实现 INewWizard 接口必须使用最后一个方法 init()。接下来,本文将介绍此方法以及此模板中自动包括的其余方法。addPages() 方法addPages() 方法将把页面添加到向导中。清单 2 中所示的方法将把单个页面添加到向导 NewXHTMLFileWizardPage 中。清单 2. addPages() 方法将把页面添加到向导中/* * Adding the page to the wizard. */public void addPages() page = new NewXHTMLFileWizardPage(selection);/ You can add more pages here.addPage(page);NewXHTMLFileWizardPage 类包含为用户提供指定页面名称功能的控件。您可以稍后把控件添加到页面中,使最终用户可以输入更多信息。performFinish() 方法当用户单击向导中的 Finish 按钮时将调用 performFinish() 方法。在执行一些检查之后,它将使用 IRunnableWithProgress 接口调用 doFinish() 方法。使用此接口意味着在执行 doFinish() 方法时(在本例中需要花很长时间运行)不必编写显示进度条的所有 UI 元素。下面完整地列出了该方法。清单 3. performFinish() 方法/* * This method is called when Finish button is pressed in * the wizard. We will create an operation and run it * using wizard as execution context. */public boolean performFinish() final String containerName = page.getContainerName();final String fileName = page.getFileName();IRunnableWithProgress op = new IRunnableWithProgress() public void run(IProgressMonitor monitor) throws InvocationTargetException try doFinish(containerName, fileName, monitor); catch (CoreException e) throw new InvocationTargetException(e); finally monitor.done();try getContainer().run(true, false, op); catch (InterruptedException e) return false; catch (InvocationTargetException e) Throwable realException = e.getTargetException();MessageDialog.openError(getShell(), Error, realException.getMessage();return false;return true;doFinish() 方法 如下所示,doFinish() 方法将创建新文件并通过 IDE 中的编辑器打开新文件。将调用 openContentStream() 方法以获得给新文件填充内容的输入流。清单 4. 初始的 doFinish() 方法/* * The worker method. It will find the container, create the * file if missing or just replace its contents, and open * the editor on the newly created file. */private void doFinish(String containerName,String fileName,IProgressMonitor monitor)throws CoreException / create a sample filemonitor.beginTask(Creating + fileName, 2);IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();IResource resource = root.findMember(new Path(containerName);if (!resource.exists() | !(resource instanceof IContainer) throwCoreException(Container + containerName + does not exist.);IContainer container = (IContainer) resource;final IFile file = container.getFile(new Path(fileName);try InputStream stream = openContentStream();if (file.exists() file.setContents(stream, true, true, monitor); else file.create(stream, true, monitor);stream.close(); catch (IOException e) monitor.worked(1);monitor.setTaskName(Opening file for editing.);getShell().getDisplay().asyncExec(new Runnable() public void run() IWorkbenchPage page =PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();try IDE.openEditor(page, file, true); catch (PartInitException e) );monitor.worked(1);openContentStream() 方法如下所示,openContentStream() 方法将返回包含生成的静态字符串作为模板一部分的 ByteArrayInputStream。对于本文,字符串将被替换为模板文件的内容。此方法中的代码是首先必须更改的,这样才能在创建时允许把更多有用的内容添加到新文件中。清单 5. openContentStream() 方法/* * Initialize file contents with a sample text. */private InputStream openContentStream() String contents =This is the initial file contents for *.html +file that should be word-sorted in the Preview +page of the multi-page editor;return new ByteArrayInputStream(contents.getBytes();添加基本内容新文件的内容不使用静态字符串值,您可以使用 getResourceAsStream() 方法把文件的内容载入到 InputStream 中,并且 doFinish() 方法可以用它来填充新文件。请做出如下所示的修改。清单 6. 从资源获得输入流/* * Initialize the file contents to contents of the * given resource. */private InputStream openContentStream() return this.getClass().getResourceAsStream(templates/index-xhtml-template.resource);index-xhtml-template.resource 文件中是有效的可扩展超文本标记语言(Extensible Hypertext Markup Language,XHTML)V1.0 Strict Web 页面。它有针对一组模拟企业样式表和 JavaScript 文件的一些基本标记和点。该文件列于清单 7 中。此文件与 NewXHTMLFileWizard 类在同一个包中,因此在本文中此文件位于 com.example.eclipse.wizards 包中。如果需要将文件放在其他包中,则可以像访问目录内的文件一样访问它(即,com.example.resources 是 /com/example/resources)。清单 7. index-xhtml-template.resource 文件This is an E Web page Main menuHomeItem 1现在,您可以运行 Eclipse 插件来查看该插件的内容。测试新向导在 Eclipse 创建向导所使用的三个类之后,您可以在阅读本文的过程中随时启动另一个 Eclipse 实例来运行和测试插件。要启动插件项目,请在项目上右击,并选择 Run As Eclipse Application,如图 6 所示。Eclipse 的新实例将启动。图 6. 将项目作为 Eclipse 应用程序来运行现在需要创建包含新文件的临时项目。项目的名称无关紧要 诸如 “temp” 之类的名称即可。当新项目已在工作区中后,请通过选择 File New Other 来添加新模板。如果一切按预期运行正常,则新类别将列于您为向导定义的类别下的 Select a Wizard 窗口中。我使用了 E 企业模板,如下所示:图 7. 使用新模板当您完成向导的其余部分后,Eclipse 将创建包含定义内容的新文件。如果此简单功能就是模板所需的全部功能,则可以止于此处。但是,可能还需要提示用户提供一些用来整合文件内容的输入。自定义向导页面初始 NewXHTMLFileWizardPage 的表单中只有两个控件:一个用于容器(项目或文件夹)的名称,而另一个用于创建新文件时使用的名称。createControl() 方法(完整的方法代码如清单 8 所示)负责创建这些控件和将其添加到对话框中。清单 8. createControl() 方法/* * see IDialogPage#createControl(Composite) */public void createControl(Composite parent) Composite container = new Composite(parent, SWT.NULL);GridLayout layout = new GridLayout();container.setLayout(layout);layout.numColumns = 3;layout.verticalSpacing = 9;Label label = new Label(container, SWT.NULL);label.setText(&Container:);containerText = new Text(container, SWT.BORDER | SWT.SINGLE);GridData gd = new GridData(GridData.FILL_HORIZONTAL);containerText.setLayoutData(gd);containerText.addModifyListener(new ModifyListener() public void modifyText(ModifyEvent e) dialogChanged(););Button button = new Button(container, SWT.PUSH);button.setText(Browse.);button.addSelectionListener(new SelectionAdapter() public void widgetSelected(SelectionEvent e) handleBrowse(););label = new Label(container, SWT.NULL);label.setText(&File name:);fileText = new Text(container, SWT.BORDER | SWT.SINGLE);gd = new GridData(GridData.FILL_HORIZONTAL);fileText.setLayoutData(gd);fileText.addModifyListener(new ModifyListener() public void modifyText(ModifyEvent e) dialogChanged(););initialize();dialogChanged();setControl(container);必须先在文件的顶部声明新控件和其他控件,然后才可以将新控件添加到此方法中。 清单 9. 声明新控件public class NewXHTMLFileWizardPage extends WizardPage /* Newly added for the page title */private Text titleText;/ the rest of the class.现在添加文本的 getter。NewXHTMLFileWizard 类将在构建新文件时使用此 getter。getTitle() 方法如下所示:清单 10. getTitle() 方法/* * Gets the HTML title for the new file */public String getTitle() return titleText.getText();修改 createControl() 方法以添加标题的新输入控件和标签。新代码如下所示:清单 11. 修改后的 createControl() 方法/* * see IDialogPage#createControl(Composite) */public void createControl(Composite parent) Composite container = new Composite(parent, SWT.NULL);GridLayout layout = new GridLayout();container.setLayout(layout);layout.numColumns = 3;layout.verticalSpacing = 9;Label label = new Label(container, SWT.NULL);label.setText(&Container:);containerText = new Text(container, SWT.BORDER | SWT.SINGLE);GridData gd = new GridData(GridData.FILL_HORIZONTAL);containerText.setLayoutData(gd);containerText.addModifyListener(new ModifyListener() public void modifyText(ModifyEvent e) dialogChanged(););Button button = new Button(container, SWT.PUSH);button.setText(Browse.);button.addSelectionListener(new SelectionAdapter() public void widgetSelected(SelectionEvent e) handleBrowse(););label = new Label(container, SWT.NULL);label.setText(&File name:);fileText = new Text(container, SWT.BORDER | SWT.SINGLE);gd = new GridData(GridData.FILL_HORIZONTAL);fileText.setLayoutData(gd);fileText.addModifyListener(new ModifyListener() public void modifyText(ModifyEvent e) dialogChanged(););/* Need to add empty label so the next two controls * are pushed to the next line in the grid. */label = new Label(container, SWT.NULL);label.setText();/* Adding the custom control here */label = new Label(container, SWT.NULL);label.setText(&Title:);titleText = new Text(container, SWT.BORDER | SWT.SINGLE);gd = new GridData(GridData.FILL_HORIZONTAL);titleText.setLayoutData(gd);titleText.addModifyListener(new ModifyListener() public void modifyText(ModifyEvent e) dialogChanged(););/* Finished adding the custom control */initialize();dialogChanged();setControl(container);在将代码添加到 NewXHTMLFileWizard 类中之前,请通过执行先前概述的步骤测试到目前为止的更改。验证用户输入用户在新向导的 Title 字段中输入的文本将用作新 HTML 文件的 元素中的文本。出于本文的目的,该值是必需的,因此需要添加检查输入的代码以确保用户输入的内容是没有问题的。对 dialogChanged() 方法的修改如下所示:清单 12. 检验 dialogChanged() 中的输入/* * Ensures that both text fields are set. */private void dialogChanged() IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getContainerName();String fileName = getFileName(); String titleText = getTitle();if (getContainerName().length() = 0) updateStatus(File container must be specified);return;if (container = null| (container.getType() & (IResource.PROJECT | IResource.FOLDER) = 0) updateStatus(File container must exist);return;if (!container.isAccessible() updateStatus(Project must be writable);return;if (fileName.length() = 0) updateStatus(File name must be specified);return;if (fileName.replace(, /).indexOf(/, 1) 0) updateStatus(File name must be valid);return;int dotLoc = fileName.lastIndexOf(.);if (dotLoc != -1) String ext = fileName.substring(dotLoc + 1);if (ext.equalsIgnoreCase(html) = false) updateStatus(File extension must be html);return; if (titleText.length() =0 )updateStatus(Title must be specified);return;updateStatus(null);完成这些更改后,如果不输入 Title 值,向导将提供错误消息。此外,Finish 按钮将被禁用,直至为 Title 指定了值为止。通过使用先前概述的步骤运行插件项目来检验此功能。添加自定义内容向导页面 NewXHTMLFileWizardPage 现在将捕捉用户输入的 HTML 标题的值,但是它尚未把该值合并到文件中。要开始将该值添加到文件中,首先需要编辑 index-xhtml-template.resource 文件使其包含该值的占位符。您可以将 元素更改为 $title,这样可以更轻松地包含占位符。修改 performFinish() 方法以从向导页面获得标题并将标题传递给 doFinish() 方法以及其余值。清单 13. 最终的 performFinish() 方法/* * This method is called when Finish button is pressed in the wizard. We * will create an operation and run it using wizard as execution context. */public boolean performFinish() final String containerName = page.getContainerName();final String fileName = page.getFileName();final String title = page.getTitle();IRunnableWithProgress op = new IRunnableWithProgress() public void run(IProgressMonitor monitor)throws InvocationTargetException try doFinish(containerName, fileName, title, monitor); catch (CoreException e) throw new InvocationTargetException(e); finally monitor.done();try getContainer().run(true, false, op); catch (InterruptedException e) return false; catch (InvocationTargetException e) Throwable realException = e.getTargetException();MessageDialog.openError(getShell(), Error, realException.getMessage();return false;return true;接下来,略微修改 doFinish() 方法使其接受标题作为参数并将其传递给 openContentStream() 方法。清单 14. 接受标题作为参数的最终 doFinish() 方法/* * The worker method. It will find the container, create the file if missing * or just replace its contents, and open the editor on the newly created * file. */private void doFinish(String containerName, String fileName, String title,IProgressMonitor monitor) throws CoreException monitor.beginTask(Creating + fileName, 2);IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();IResource resource = root.findMember(new Path(containerName);if (!resource.exists() | !(resource instanceof IContainer) throwCoreException(Container + containerName+ does not exist.);IContainer container = (IContainer) resource;final IFile file = container.getFile(new Path(fileName);try InputStream stream = openContentStream(title);try if (file.exists() file.setContents(stream, true, true, monitor); else file.create(stream, true, monitor); finally stream.close(); catch (IOException e) monitor.worked(1);monitor.setTaskName(Opening file for editing.);getShell().getDisplay().asyncExec(new Runnable() public void run() IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();try IDE.openEditor(page, file, true); catch (PartInitException e) );monitor.worked(1);最后,需要修改 openContentStream() 方法的很大一部分才能够将文件中的 $title 值替换为用户提供的值(参见清单 15)。在配有大量不同值的模板中,您可以使用更精确的解决方案,例如扩展 FilterInputStream 并替换一整组不同值的新类。 清单 15. 最终的 openContentStream() 方法/* * Initialize the file contents to contents of the given resource. */private InputStream openContentStream(String title)throws CoreException final String newline = ; / System.getProperty(line.separator);String line;StringBuffer sb = new StringBuffer();try InputStream input = this.getClass().getResource

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论