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 delete all items except the last. This gives a NullPointerException. How to fix it?

+5
source share
9 answers

The code in the question usually works. However, this seems like a threading issue. Another thread can ruin the elements.

However, I want you to use the method better removeAllItems();:

combo.removeAllItems();
+26
source
+3
source

:

combo.removeItemAt(0);

, 0 i.

:

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

combo.removeAllItems()

+2

.removeAllItems() .

+1

, , . , .

- , , - , .

, - ( actionPeformed()) combo.removeItemAt(0) removeAllItems(), actionPerformed /. actionPerformed() ( - ). , , , actionPerformed() .

, actionPerformed(), . mouseClicked() , .

0

removeAllItems () it removes everything, but after adding data to the combo box it will not be displayed there, a nullPointException will show

0
source

Use this to remove all items from a combo box:

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

This usually happens because you have an event related to JComboBox. It is resolved if you have a control in JComboBox, 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 ();
  }
}
0
source

You can use

this.combo.removeAllItems ();

delete all items in JComboBox.

0
source

All Articles