在ide開發中,我們經常可能會需要預覽Java代碼(可能自己提供的java代碼模板),jdt中已經提供了這樣的支援,支援文法高亮等,它本質上是對TextViewer的封裝。可能如下:
JavaPreview是抽象類別,我們可以使用其子類 org.eclipse.jdt.internal.ui.preferences.formatter.CompilationUnitPreview.直接上代碼:
/** * Create contents of the dialog. * * @param parent */@Overrideprotected Control createDialogArea(Composite parent) {Composite container = (Composite) super.createDialogArea(parent);getShell().setText("預覽Java代碼");// 建立javapreview執行個體CompilationUnitPreview preview = new CompilationUnitPreview(JavaCore.getDefaultOptions(), container);preview.getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); String filePath = "src/net/chenxs/JNIBindingsTestApp.java";IFile file = ResourcesPlugin.getWorkspace().getRoot().getProject("test").getFile(filePath);String content = "";try {content = readString(file, ResourcesPlugin.getEncoding());} catch (CoreException e) {e.printStackTrace();}preview.setPreviewText(content);// 設定java代碼內容preview.update();// 顯示格式化後內容return container;}