Removing all Items from a combo box in Java

别说谁变了你拦得住时间么 提交于 2019-12-03 08:04:59

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();
Asad

In second line:

combo.removeItemAt(0);

I think instead of 0 it should be i.

do it in reverse order as:

for(int i=combo.getItemCount()-1;i>=0;i--){
    combo.removeItemAt(i);
}

But in my case combo.removeAllItems() works fine

You can use

this.combo.removeAllItems();

to remove all the items in JComboBox.

use .removeAllItems() methods to remove all items from combo box.

The assumption that it is related to another thread is not always true. It can be the thread itself causing the issue.

This exception may happen because an event is triggered when a combo item is removed and in this event handling method you still refer to combobox items.

For example when you delete somewhere (other than in actionPeformed()) in your code the last item from a combo box with combo.removeItemAt(0) or removeAllItems() then still the event actionPerformed will be fired/executed. But very often the actionPerformed() method contains code to react on user actions (user clicked somewhere on the combobox). So, when the last item has been deleted there is no more item in the combobox and any reference to an item or index in actionPerformed() will cause an exception.

The solution to this is to move the code from actionPerformed() to e.g. mouseClicked() or another event handler depending on what you want to do.

removeAllItems() it does remove all things but after the add data to the combo box it will not show there ,the nullPointException will shows

SBS

Use this to remove all the elements from the combo box :

DefaultComboBoxModel model = (DefaultComboBoxModel) ComboBox.getModel();
model.removeAllElements();

Usually it happens because you have an event associated JComboBox. It is solved if you have control item in the JComboBox to act, for example:

jComboBoxExample.addActionListener (new ActionListener () {
   public void actionPerformed (ActionEvent e) {
     do_run ();
   }
});



public void do_run() {
  int n=jComboBoxPerfilDocumentos.getItemCount(); <--THIS IS THE SOLUTION
  if (n> 0) { 
    String x = jComboBoxPerfilDocumentos.getSelectedItem (). ToString ();
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!