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

问题描述 投票:1回答:2

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

        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无法解析为变量。可能是什么问题?

java eclipse plugins eclipse-plugin
2个回答
1
投票

根据https://wiki.eclipse.org/FAQ_How_do_I_open_an_editor_on_a_file_in_the_workspace%3F,实际上有一个更直接的解决方案

int lineNumber = ...
IPath path = ...
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
IMarker marker = file.createMarker(IMarker.TEXT);
marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IDE.openEditor(page, marker);
marker.delete();

4
投票

这是因为在完成条件时,嵌套在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));
}

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

© www.soinside.com 2019 - 2024. All rights reserved.