JavaFX:TextArea 光标移回新文本的第一行

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

我很难使用 TextArea 的光标,在向 Textarea.[=17= 添加新文本后,它一直设置在第一行的位置 0 ]

问题背景

我有一个 Textarea,当我添加足够多的文本时,会出现一个滚动条,将新文本置于旧文本下方。到这里为止一切正常,但是,TextArea 中的光标会回到顶部,这在我频繁插入 TextArea 时变得很烦人。

以下是我每次添加新行的方式:

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

如何在每次插入后停止 TextArea 中的光标回到第一行?

如果你想追加到 TextArea 的末尾,你可以使用 appendText 而不是 setText:

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

这将自动滚动到底部并将插入符号置于文本末尾。


注意:一点背景知识。

TextInputControl的代码中,appendText将调用insertText作为insertText(getLength(), text);,因此textArea.appendText(str + "\n");textArea.insertText(textArea.getLength(), str + "\n");是相等的。 insertText 会将插入符位置设置为 insertationPosition + insertedText.getLength(),这就是插入符移到末尾的原因。

我也遇到了同样的问题,我得到了解决方案。我正在编写一个记事本,我必须在单击 "Open" 菜单项时打开文本文件。在另一个函数中,我对其进行编码。

@FXML
private void openaFile(ActionEvent event) throws FileNotFoundException, IOException {
    Stage window=new Stage();
    FileChooser fc=new FileChooser();
    File sf=fc.showOpenDialog(window);
    if(sf!=null){
               FileReader fr=new FileReader(sf);
               Scanner sc=new Scanner(fr);

               while(sc.hasNext()){
                         text.appendText(sc.next());
                         text.appendText("\n");
              }  
    }

}