-1

For a highschool project I created a for loop that displays the 5 songs I initialised. I put it under the a button called btnInitializeActionPerformed so when the initialized button is pressed, it displays the songs, however it only displays the last song, what am I doing wrong?

Here is the loop

Collections.addAll (strSongArtist, "Dont Stop Believing", "this", "hello",  "Think", "No");

for (int i = 0; i < strSongArtist.size(); i++) {
       String valueContent = strSongArtist.get(i);
       txtOutput.setText( valueContent);
}

when I display strSongArtist like this in side the for loop:

System.out.println(strSongArtist.get(i));

Btw my teacher gave an example of outputing the code like this:

txtOutput.setText( strSongArtist.get(rn.nextInt(strSongArtist.size())).toString());

but I have no idea how to use this either?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • What is txtOutput? A JTextField? A JTextArea? You're replacing any String in that text component with the next String, so only the last shows. If a JTextArea, you want to use append not setText. – Hovercraft Full Of Eels Jul 21 '16 at 13:45
  • `txtOutput.setText( valueContent);` will replace the text instead of appending. One simple (yet not optimal or well designed) solution to this would be `txtOutput.setText( txtOutput.getText() + ", " + valueContent);`. – Thomas Jul 21 '16 at 13:45

2 Answers2

0

Every time the loop runs it is setting the text of txtOutput to the value of the valueContent, so it will display the last artist at the end of the loop. You should at least create a string and append each artist to it and set the text at the end of the loop

String artists = "";
for (int i = 0; i < strSongArtist.size(); i++) {
       artists += strSongArtist.get(i) + ", ";
}
 txtOutput.setText( artists );
Colonel Mustard
  • 1,482
  • 2
  • 17
  • 42
0

Your problem is that you are calling txtOutout.setText() during each loop iteration.

So, even if textOutput is some label/panel whatsoever that would be able to display more than string ... what you are doing is that you are telling it to only display that one string that you are passing to it.

Meaning: you have a loop that produces 5 individual strings. If you want those 5 strings to show up together, you have to build something that contains all those 5 individual strings.

You can either do that by collecting the results of your "get(i)" calls using a StringBuffer; or you call setTest() with the result of "getText() + "\n" + get(i)" ...

GhostCat
  • 137,827
  • 25
  • 176
  • 248