2011-07-26 46 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

如果不在編輯器中選擇一個部分,我真的無法獲得位置嗎? –

相關問題