• Post Reply Bookmark Topic Watch Topic
  • New Topic

JComboBox.removeAllItems() seems to remove more than just comboBox items  RSS feed

 
Gretchen Frye
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you create a JComboBox with a Vector, JComboBox.removeAllItems remove items not only from the comboBox list, but also from the vector itself. But if you create the JComboBox with an array, it removes items from the comboBox but leaves the array alone, as you would expect. JavaDoc for removeAllItems simply says it will "Removes all items from the item list." Is this as intended, and if so, can you explain why it makes sense, because it doesn't to me.



Results below; when JComboBox is created with a vector, cb.removeAllItems() removes the items from the comboBox *and* the vector:

Create JComboBox with an array
Before cb.removeAllItems(), Colorlist vector has 4 items. ComboBox has 4 items.
After cb.removeAllItems(), Colorlist vector has 4 items. ComboBox has 0 items.

Create JComboBox with a Vector
Before cb.removeAllItems(), Colorlist vector has 4 items. ComboBox has 4 items.
After cb.removeAllItems(), Colorlist vector has 0 items. ComboBox has 0 items.

 
Rob Camick
Ranch Hand
Posts: 2756
12
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Swing components work with Models.

When you create a JComboBox it will use the DefaultComboBoxModel to hold the data.

When you create a combo box with a Vector, then the DefaultComboBoxModel will just use the Vector as the internal storage for the data. So when you add/remove items for the model you are actually updating the Vector.

When you create a combo box with an Array, the DefaultComboxBox will create its own internal Vector and copy all the items from the Array to the Vector. So in this case the internal Vector of the model is different than the external Array.

This is why when you work with Swing models you should always update the model directly and never attempt to update the external source where the data originally came from.
 
Gretchen Frye
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, that makes sense.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!