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

只愿长相守 提交于 2020-01-24 21:05:12

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/43886613/javafx-textarea-cursor-moves-back-to-the-first-line-on-new-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!