Search code examples
javajavafxcursortextarea

JavaFX: TextArea cursor moves back to the first line on new text


I'm having a hard time with TextArea's cursor, it keeps being set to position 0 in the first line, after adding new text to the Textarea.

Problem Background

I have a Textarea, when I add enough text a scroll bar appears to put the new text below the old one. Until here everything is OK, however, the cursor in the TextArea comes back to the top which becomes annoying when I have frequent insertions to the TextArea.

Here is how I add the new line each time:

void writeLog(String str) {
    textArea.setText(textArea.getText() + str + "\n");
}

How can I stop the cursor in the TextArea from going back to the first line after each insertion?


Solution

  • If you want to append to the end of the TextArea you can use appendText rather than setText:

    textArea.appendText(str + "\n");
    

    This will automatically scroll to the bottom and place the caret to the end of the text.


    Note: A little background.

    In the code of TextInputControl, appendText will call insertText as insertText(getLength(), text); therefore textArea.appendText(str + "\n"); and textArea.insertText(textArea.getLength(), str + "\n"); are equal. insertText will set the caret position as insertationPosition + insertedText.getLength(), that's why the caret is moved to the end.