2017-09-02 50 views
1

我在JTextArea中設置了一些文字。光標位於第5行。現在我想在第一行設置一些文本。如何在TextArea中重新定位光標

那麼是否可以將光標重新定位到所需的行?

+0

標題說'JTextField',但正文說'JTextArea'。這是什麼? –

回答

2

使用JTextComponent.setCaretPosition(int)其中:

設置TextComponent的文本插入符的位置。請注意,脫字符跟蹤改變,所以如果組件的基礎文本被改變,這可能會移動。如果文檔是null,則什麼都不做。該位置必須介於0和組件文本的長度之間,否則會引發異常。

2

如果你想從一個實際的文本行去另一個文本行,那麼你還需要使用JTextComponent.setCaretPosition()方法,但你還需要的是獲得所需的線起點的手段索引傳遞給JTextComponent.setCaretPosition()方法。這裏是你如何能得到所提供的任何行號的起始索引提供的文檔中提供的行號存在:

public int getLineStartIndex(JTextComponent textComp, int lineNumber) { 
    if (lineNumber == 0) { return 0; } 

    // Gets the current line number start index value for 
    // the supplied text line. 
    try { 
     JTextArea jta = (JTextArea) textComp; 
     return jta.getLineStartOffset(lineNumber-1); 
    } catch (BadLocationException ex) { return -1; } 
} 

如何使用上面的方法(假設從的actionPerformed事件一個JButton的):

int index = getLineStartIndex(jTextArea1, 3); 
if (index != -1) { 
    jTextArea1.setCaretPosition(index); 
} 
jTextArea1.requestFocus(); 

示例用法代碼上面將移動插入符號(無論從任何位置它正好文檔)至3線的同一文檔中的開頭內是英寸

編輯:基於註釋中的問題...

要移動插入符號到行的末尾,你可以讓另一方法非常類似於getLineStartIndex()方法除了上面現在我們將其命名爲getLineEndIndex(),我們會做一個單一的代碼行的變化:

public int getLineEndIndex(JTextComponent textComp, int lineNumber) { 
    if (lineNumber == 0) { return 0; } 

    // Gets the current line number end index value for 
    // the supplied text line. 
    try { 
     JTextArea jta = (JTextArea) textComp; 
     return jta.getLineEndOffset(lineNumber-1) - System.lineSeparator().length(); 
    } catch (BadLocationException ex) { return -1; } 
} 

使用此方法的方法與上面顯示的getLineStartIndex()方法相同。

+0

它正在工作,但是我們能否將光標移動到行尾?用此代碼光標在行首。 – Anukool

+0

@Anukool - 請參閱上面的答案中的**編輯**。 – DevilsHnd