java - 在Eclipse插件中打开文件到某一行

标签 java eclipse plugins eclipse-plugin

我正在编写一个插件,该插件必须在按下按钮时在特定行打开文件。 我有以下代码在特定行打开文件。

        String filePath = "file path" ;
            final IFile inputFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(Path.fromOSString(filePath));
            if (inputFile != null) {
                IWorkbenchPage page1 = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                IEditorPart openEditor11 = IDE.openEditor(page1, inputFile);
            }


            int Line = 20;

                    if (openEditor11 instanceof ITextEditor) {
                        ITextEditor textEditor = (ITextEditor) openEditor ;
                        IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
                        textEditor.selectAndReveal(document.getLineOffset(Line - 1), document.getLineLength(Line-1));
                    }

我的问题是 if 语句中的变量 openEditor11 给出了错误:openEditor11 cannot be resolved to a variable。可能是什么问题?

最佳答案

那是因为嵌套在 if 语句中的变量声明在完成条件时超出了范围。因此变量被释放,并且在你的第二个语句中,不再存在。

你应该事先声明它以避免这样的错误:

IEditorPart openEditor11;
String filePath = "file path" ;
final IFile inputFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(Path.fromOSString(filePath));
if (inputFile != null) {
    IWorkbenchPage page1 = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    openEditor11 = IDE.openEditor(page1, inputFile);
}


int Line = 20;

if (openEditor11 instanceof ITextEditor) {
    ITextEditor textEditor = (ITextEditor) openEditor ;
    IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
    textEditor.selectAndReveal(document.getLineOffset(Line - 1), document.getLineLength(Line-1));
}

到达第二个条件 block 时,如果第一个条件不适用,编辑器可能为空,但这不是问题,因为 instanceof 在空值上返回 false。

关于java - 在Eclipse插件中打开文件到某一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25420780/

相关文章:

java - S3上传String的用户元数据列表

导出后 Java 应用程序无法启动

Java 正则表达式 - 带一个反斜杠的无效转义序列,使用两个删除这些标记

java - Java EE 项目中的错误

java - jdom性能

java - Websphere Application Server Network Deployment v7(非社区版)中的 servlet 容器是什么?

java - 访问存储在 Java 列表中的对象属性并进行迭代

javascript - 如何从代码中以管理员身份运行 Chrome

objective-c - 错误预期标识符或 (

javascript - 通过完全集成在 Monaco Editor 中扩展 JavaScript 语法