JavaPreview类的使用(预览Java代码)

来源:互联网 发布:js分割反斜杠字符串 编辑:程序博客网 时间:2024/05/17 22:45

在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;}

原创粉丝点击