You can write your own function to append text. In this method you can use setText
, rather than appendText
as appendText
automatically scrolls to the end of the content (setText
scrolls to the beginning but this can be supressed by setting back the scrollTopProperty
to its previous value).
Example
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,400,400);
TextArea ta = new TextArea();
root.setCenter(ta);
Button button = new Button("Append");
button.setOnAction(e -> {
appendTextToTextArea(ta, "BlaBlaBla\n");
});
root.setBottom(button);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
/**
* Appends text to the end of the specified TextArea without moving the scrollbar.
* @param ta TextArea to be used for operation.
* @param text Text to append.
*/
public static void appendTextToTextArea(TextArea ta, String text) {
double scrollTop = ta.getScrollTop();
ta.setText(ta.getText() + text);
ta.setScrollTop(scrollTop);
}
}
Note:
Alternatively you can also extend TextArea
and overload appendText
to be able to specify whether you want to move the scrollbar:
public class AppendableTextArea extends TextArea {
public void appendText(String text, Boolean moveScrollBar) {
if (moveScrollBar)
this.appendText(text);
else {
double scrollTop = getScrollTop();
setText(getText() + text);
setScrollTop(scrollTop);
}
}
}
and the usage:
AppendableTextArea ta = new AppendableTextArea();
ta.appendText("BlaBlaBla\n", false);