JavaFX:TextArea光标移回新文本的第一行 [英] JavaFX: TextArea cursor moves back to the first line on new text
问题描述
我在使用 TextArea
的光标时遇到了麻烦,将新文本添加到<$ c之后,它一直被设置为第一行的位置0。 $ c> Textarea 。
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
.
问题背景
我有一个 Textarea
,当我添加足够的文本时,会出现一个滚动条,将新文本放在旧文本下方。直到此处一切正常,但是 TextArea
中的光标返回顶部,当我频繁插入 TextArea 时,这变得很烦人
。
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");
}
如何在 TextArea
从每次插入后返回第一行?
How can I stop the cursor in the TextArea
from going back to the first line after each insertion?
推荐答案
如果要追加到 TextArea
的末尾,可以使用 appendText
而不是 setText
:
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.
注意:有一点背景知识。
在 TextInputControl
的代码中,将调用 appendText
insertText
作为 insertText(getLength(),text);
因此 textArea.appendText(str + \n);
和 textArea.insertText(textArea.getLength(),str + \n);
相等。 insertText
会将插入标记的位置设置为 insertationPosition + insertedText.getLength()
,这就是插入标记移至末尾的原因
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.
这篇关于JavaFX:TextArea光标移回新文本的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!