2011-07-26 47 views
7

我一直在尝试获取文本编辑器中光标位置的行号和列号。我试过函数getCursorPosition()。但是在打印时,它只显示“?”。请注意,我需要编辑器中的行号和列号,而不是屏幕。 我看到有一个函数JTextArea.getCaretPosition。但我不知道如何将文本编辑器转换为JTextArea。 另外,是否可以读取放置光标的单词?如何获取光标在日蚀文本编辑器中的位置

谢谢

回答

8

从TextEditor中,您可以获取文档,文档提供程序和选择。这将让你访问当前的游标偏移量。

ITextEditor editor = (ITextEditor) editorPart 
     .getAdapter(ITextEditor.class); 
IDocumentProvider provider = editor.getDocumentProvider(); 
IDocument document = provider.getDocument(editorPart 
     .getEditorInput()); 
ITextSelection textSelection = (ITextSelection) editorPart 
     .getSite().getSelectionProvider().getSelection(); 
int offset = textSelection.getOffset(); 
int lineNumber = document.getLineOfOffset(offset); 

IDocument提供了其他方法来获得线的开始(你可以计算出从该列)。

欲了解更多信息,请参阅http://wiki.eclipse.org/The_Official_Eclipse_FAQs#Text_Editors

+0

越野车,因为转换是不检查 – Chameleon

+0

记住,这并没有得到实际的插入符的位置,但选择的。脱字符可以位于选择的任一端。 – Lii

+1

如果不在编辑器中选择一个部分,我真的无法获得位置吗? –

相关问题