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]
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.
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.
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.
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.
精彩评论