why this code about combobox doesn't work?

≡放荡痞女 提交于 2019-12-11 16:13:36

问题


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]


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/1796990/why-this-code-about-combobox-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!