Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all Items from a combo box in Java

I need to remove all items from the combo box

int itemCount = combo.getItemCount();

for(int i = 0; i < itemCount; i++){
  combo.removeItemAt(0);
}

This code will remove all items except the last one. It gives a NullPointerException. How to fix that?

like image 221
chathura Avatar asked Sep 03 '12 13:09

chathura


People also ask

How do I remove items from a combobox in Java?

removeItem(Object anObject) Removes an item from the item list. Just call that to remove the object you no longer want.

How do you make an editable combo box in Java?

By default, the user not allowed to edit the data in the text field portion of the JComboBox. If we want to allow the user to edit the text field, call setEditable(true) method. A JComboBox can generate an ActionListener, ChangeListener or ItemListener when the user actions on a combo box.

What is combobox control in Java?

A component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value.


1 Answers

The code in the question would normally work. However, it looks like a threading issue. Another thread may be messing with the items.

However, I sugeest you should better use the removeAllItems(); method:

combo.removeAllItems();
like image 165
Dan D. Avatar answered Oct 03 '22 10:10

Dan D.