Alpha2k
Alpha2k

Reputation: 2241

Looping through collection

I got a problem with this code:

for (String functionChain : stringCollection) {
 lblSource.setText(functionChain);
 System.out.print(functionChain);
}

I want to set the text to lblSource as a "chain" of all the collected strings.
It does work with the System.out , i mean it does output as I want but it doesnt Set the Text to the Label, it only sets the LAST valor of the array.
Why is this happening? I mean, the system.out is fine and i am taking same variable "functionChain"... However the output is different in the system.out as in the label.

Upvotes: 0

Views: 84

Answers (3)

ranjit
ranjit

Reputation: 158

lblSource.setText(functionChain) will over write the existing value with new value.

To have all the values of string collection , loop through the string collection , append the values and then set the value to lblSource.

eg :

StringBuilder sb = new StringBuilder();

loop through the collection.

sb.append(each value);
sb.append (",") // a separator if required

then

lblSource.setText(sb.toString()) 

Upvotes: 0

Cody S
Cody S

Reputation: 4824

setText() does what it sounds like it does: it sets the text of the label.

Try this instead:

String s = "";
for (String functionChain : stringCollection) {
    s += functionChain;
    System.out.print(functionChain);
}
lblSource.setText(s);

Upvotes: 2

Kayaman
Kayaman

Reputation: 73558

Get the old value first and concatenate.

lblSource.setText(lblSource.getText() + functionChain);

Upvotes: 4

Related Questions