Removing all Items from a combo box in Java

前端 未结 9 1168
自闭症患者
自闭症患者 2021-02-06 11:04

I need to remove all items from the combo box

    int itemCount = combo.getItemCount();

    for(int i=0;i

        
相关标签:
9条回答
  • 2021-02-06 11:12

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

    0 讨论(0)
  • 2021-02-06 11:12

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

    DefaultComboBoxModel model = (DefaultComboBoxModel) ComboBox.getModel();
    model.removeAllElements();
    
    0 讨论(0)
  • 2021-02-06 11:20

    How about JComboBox.removeAllItems()?

    0 讨论(0)
  • 2021-02-06 11:22

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

    0 讨论(0)
  • 2021-02-06 11:27

    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.

    0 讨论(0)
  • 2021-02-06 11:28

    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 ();
      }
    }
    
    0 讨论(0)
提交回复
热议问题