我正在编写一个插件,该插件必须在按下按钮时在特定行打开文件。 我有以下代码在特定行打开文件。
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/