1

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.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366

2 Answers2

3

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());
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • @SpencerSalomons If you want to use this in a loop, then create the `StringBuilder` outside the loop, append all the text to the `StringBuilder` in the loop, and eventually, after the loop append the `StringBuilder.toString()` to the textarea. Recreating a new `StringBuilder` in every iteration is useless as this unefficient and is what the java compiler does anyway when using the `+` operator on `String`. – Guillaume Polet Apr 02 '15 at 22:43
  • @GuillaumePolet Good advice, but I was under the impression that Java didn't optimise `String` concatenation within loops, or is that to do with concatenating a `String` defined outside the loop? – MadProgrammer Apr 02 '15 at 22:45
  • 1
    @MadProgrammer When you use String concatenation with the `+` operator (something like `a + b`, where a and b are `String`), the compiler nicely does `new StringBuilder().append(a).append(b).toString()` for you. Of course, in a loop, this becomes awfully unefficient, because you keep on recreating `StringBuilder` and `String`, while the `StringBuilder` could be re-used through every iteration of the loop and create only a single `String` at the end. This is also explained [here](http://stackoverflow.com/a/1532483/928711) – Guillaume Polet Apr 02 '15 at 22:48
1

Just guessing but...

String oldText = outputBox.getText();
outputBox.setText(oldText + j + ": " + song.get(j));
posit labs
  • 8,951
  • 4
  • 36
  • 66