zoey3
zoey3

Reputation: 171

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.

Upvotes: 6

Views: 28231

Answers (3)

Daniel De Le&#243;n
Daniel De Le&#243;n

Reputation: 13639

Another way is by using the appendText method

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

Upvotes: 3

Reporter
Reporter

Reputation: 3948

The method .setText() puts only one value into the field. If a value exists, the old one will be replaced. Try:

private StringBuilder fieldContent = new StringBuilder(""); 
for (int i=1;i<=5;i++)
 {
   //Concatinate each loop 
   fieldContent.append("    Field "+i+"\n");
 }
 ta.setText(fieldContent.toString());

That is one way to achive it.

Upvotes: 6

Peanut
Peanut

Reputation: 3963

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.

Upvotes: 4

Related Questions