Spencer Salomons
Spencer Salomons

Reputation: 13

How to set text in a JTextArea without replacing what's there?

How would I use

for (int j = 0; j < song.size(); j++)  {
    outputBox.setText(j + ": " + song.get(j));
}

To display all the items in an array, rather than replacing them as it goes and leaving the last one? Using java.

Upvotes: 1

Views: 1326

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347204

You should use JTextArea#append...

outputBox.append(j + ": " + song.get(j));

But you'll probably also want to include a new line character at the end

outputBox.append(j + ": " + song.get(j) + "/n");

See JTextArea#append and How to Use Text Areas for more details

It may be more efficient to use a StringBuilder and the set the text of the text area after the fact

StringBuilder sb = StringBuilder(128);
for (int j = 0; j < song.size(); j++)  {
    sb.append(j).
       append(":").
       append(song.get(j)).
       append("/n");
}
outputBox.setText(sb.toString());

Upvotes: 3

posit labs
posit labs

Reputation: 9431

Just guessing but...

String oldText = outputBox.getText();
outputBox.setText(oldText + j + ": " + song.get(j));

Upvotes: 1

Related Questions