Search code examples
javafxjavafx-2

Appending text into TextArea


I'm trying to create a TextArea,

@FXML 
private TextArea ta;

and what I'm trying to get :

for (int i=1; i<=5; i++) {
    ta.setText("    Field " + i + "\n");
}

but it only show the last line : Field 5.
Can anyone help. Thanks in advance.


Solution

  • When you call setText( "..."), you replace the text which is already there. So either construct your String before setting it, or append it. Try this:

    String text="";
    for (int i=1;i<=5;i++) {
        text = text + "    Field "+i+"\n";
    }
    ta.setText(text);
    

    Note: You'll probably get better performance and it's considered "good practice" to use a "StringBuilder" instead of a String to build String like this. But this should help you understand what's the problem, without making it overly complicated.