简体   繁体   中英

How would I remove a specific item from a combo box in Java?

I'm using a String array to populate a combo box with items. After an item has been selected and submitted on a button press I want it to remove the item from the combo box. My attempt was to remove the selected item from the String array first, remove all items from the combo box and repopulate it with the String array.

choice is the String array, cboChoice is the combobox, strChoice is the item getting removed

for(int i = 0; i < choice.length; i++) {
        if(choice[i].equals(strChoice)) {
            choice[i] = null;
            cboChoice.removeAllItems();
            cboChoice.addItem(choice);
        }
    }

This is as far as I've got, I don't know if there is a simpler method of doing this but I can't seem to get it working.

If you check the jComboBox Javadoc you will see

removeItem(Object anObject) Removes an item from the item list.

Just call that to remove the object you no longer want.

The code you've proposed would sort of work (although I'm not sure off hand what the jComboBox will do with the null values) but is not particularly efficient.

Since you have a String array and a JComboBox that have the same items in the same order, you can use the JComboBox.getSelectedIndex() to retrieve the index location of the selected item and remove from the JComboBox and you're array.

As a suggestion, I would make your String array an ArrayList, it's a "smarter" dynamic array and can stay better in synch with your JComboBox. Also make sure you remove from your array first, before removing from your JComboBox, otherwise the selected index could change.

An ArrayList declaration would look like this:

ArrayList<String> choice = new ArrayList<>();

Add your content to this List like so:

choice.add(yourChoice);

Removing the items would be as followed:

if (cboChoice.getSelectedIndex() > -1) {
        choice.remove(cboChoice.getSelectedIndex());
        cboChoice.getSelectedIndex();
}

Hope this helps... Also, once you understand how this works, I would suggest studying the ComboBoxModel. Certain swing controls have model objects that you can use to add/remove/modify contents without having to reference the actual control.

This code works, but there is still one issue; you can't remove the last item in the list. To solve this you could add an element to the list that you just ignore in the remove step. I have used a "" at the beginning of the list in past.

Also I would point out that most examples of JComboBox show using strings, but you can put any type of Object you want in the box. The item in the box will show Object.toString(). In many cases it is more useful and straight forward to get back the instance you want than to have to look it up in a list based on information taken from the ComboBox.

import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by bday on 4/22/15.<br>
 * <br>
 *  ItemRemovingComboBox will do something useful I'm sure
 */
public class ItemRemovingComboBox {
    private final JFrame frame = new JFrame();
    private final List<String> strings = new ArrayList<String>();
    private final JComboBox cb;
    private final ItemListener itemListener;

    public ItemRemovingComboBox()
    {
        String[] testItems = new String[] {"one", "two", "three"};
        strings.addAll(Arrays.asList(testItems));
        cb = new JComboBox(testItems);
        frame.add(cb);
        frame.setSize(200, 200);
        frame.setVisible(true);

        itemListener = new ItemListener() {
            public void itemStateChanged(ItemEvent itemEvent) {
                if (itemEvent.getStateChange() == ItemEvent.SELECTED) {
                    String item = (String) itemEvent.getItem();
                    System.out.println("Item: " + item + " removed from list");
                    removeItem(item);
                }
            }
        };
        cb.addItemListener(itemListener);
    }

    private void removeItem(String item) {
        //this step is required to keep from calling back to the listener with new selection when item is removed
        cb.removeItemListener(itemListener);
        strings.remove(item);
        cb.removeItem(item);
        cb.addItemListener(itemListener); //okay now we what to know about changes again
    }

    public static void main(String[] args) {
        new ItemRemovingComboBox();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM