完成这些更改后,如果不输入 Title 值,向导将提供错误消息。此外,Finish 按钮将被禁用,直至为 Title 指定了值为止。通过使用先前概述的步骤运行插件项目来检验此功能。
添加自定义内容
向导页面 NewXHTMLFileWizardPage 现在将捕捉用户输入的 HTML 标题的值,但是它尚未把该值合并到文件中。要开始将该值添加到文件中,首先需要编辑 index-xhtml-template.resource 文件使其包含该值的占位符。您可以将 <title> 元素更改为 <title>${title}</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); }
(编辑:aniston)
|