tags:

views:

96

answers:

4

I have a combobox which stores "Computer ,Code:21","History ,Code:31" and also the number of items can be changed.but when I write this code for getting its items:

List<String> bIHELessons = new ArrayList<String>();
for (int i=0;i<jComboBox1.getItemCount();i++) {
   String lessons = (String) jComboBox1.getItemAt(i);
   if (lessons != null&& lessons.trim().length()!=0) {
      bIHELessons.add(lessons);
      System.out.println(bIHELessons.toString());
   }
}

it will show these sentences in the console:

[Computer,Code=21]

[Computer,Code=21, History,Code:31]

+3  A: 

Because you are appending to the list with bIHELessons.add(..). Each subsequent call adds on to the already printed string.

If you want to still add to the ArrayList and print the current item that is in the ArrayList, then use System.out.println(bIHELessons.get(i)); rather than using what you are now. I also don't think you need to use toString() because your objects are already in the type string.

Change System.out.println(bIHELessons.toString()); to System.out.println(lessons); if you only want to print the string you are currently iterating on.

0A0D
Like he said, you're println statement is printing the entire contents of the List.
ChadNC
+1  A: 

From what I can see your code is doing what it should be doing. Are you wanting to know why you are seeing all items repeated with each additional call to the print screen?

That is happening because the toString() method of the List is putting all the items in the list into a single string.

Tinidian
+1  A: 

I don't think the problem is with JComboBox but rather with your expectations. System.out.println(bIHELessons.toString()); will print out the entire contents of the bIHELessons ArrayList. Since you're adding a new String to the ArrayList on each iteration, it's logical that your System.out.println(bIHELessons.toString()); would show a progressive accumulation of content.

Your question isn't clear but you may consider moving the System.out.println outside of your loop and determining if that's what you're looking for.

spork
A: 

You are printing out the ToString() representation of your entire list. If you want to print out the object you could just print out the lessons variable instead.

Vinen