JavaFX: TextArea cursor returns to first line in new text

It’s difficult for me with the TextArea cursor, it remains at position 0 on the first line, after adding new text to TextArea .

Main problem

I have a TextArea , when I add enough text, a scrollbar appears to add new text below the old one. However, while everything is in order, the cursor in TextArea returns to the top, which becomes annoying when I have frequent inserts in TextArea .

This is how I add a new line every time:

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

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

+1
source share
1 answer

If you want to add TextArea at the end, you can use appendText , not setText :

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

This will automatically scroll down and place the carriage at the end of the text.


Note: Small background.

In the TextInputControl code, appendText will call insertText as insertText(getLength(), text); , therefore textArea.appendText(str + "\n"); and textArea.insertText(textArea.getLength(), str + "\n"); are equal. insertText sets the caret position as insertationPosition + insertedText.getLength() , so the caret moves to the end.

+1
source

Source: https://habr.com/ru/post/986063/


All Articles