Appending text into TextArea
Asked Answered
P

3

6

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.

Phonography answered 16/4, 2015 at 11:21 Comment(2)
ta.setText("") before the loop, then in the loop, ta.setText(ta.getText() + " Field "+i+"\n");Condyloid
You can also use textArea.appendText(" Field "+ i +"\n"); in the loop.Phyllotaxis
C
4

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.

Coursing answered 16/4, 2015 at 11:26 Comment(1)
If I understand things correctly, the compiler would convert the code you showed into the equivalent with a StringBuilder anyway.Hypocycloid
D
6

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.

Drillmaster answered 16/4, 2015 at 11:29 Comment(0)
C
4

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.

Coursing answered 16/4, 2015 at 11:26 Comment(1)
If I understand things correctly, the compiler would convert the code you showed into the equivalent with a StringBuilder anyway.Hypocycloid
S
3

Another way is by using the appendText method

for (int i=1; i<=5; i++) {
    ta.appendText("    Field " + i + "\n");
}
Shirl answered 27/1, 2022 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.