Search code examples
javaswingjcombobox

Multiple JComboBoxes with same data, every item choosable once


I'm growing desperate here ...:

I do have a FRAME with 40 JComboBoxes. At first, they offer all the same items. If I choose on item in one specific ComboBox, it should be selected there and not be available in all the other 39 Boxes anymore.

I tried to use a ComboBoxModel for a long while, but now I think it doesnt make any sense: the Moment i remove the selected item from the model, it gets removed from the Box that it got selected in, too.

So does it make sense to do it like this:

  • Have 40 MyComboBoxes in the class GUI
  • Every MyComboBox implements an ItemListener
  • If an item is selected, the item gets removed from the other 39 lists; if its deselected, it gets added to the other 39 lists (but if I want to do it like that, the listener mustnt be an own class but the itemEventChanged-method must be implemented anonymously in the GUI?!)

There's a better way, isnt it? Thanks a lot for your help!


Solution

  •        for(int x =0;x<YourComboBoxArray.length();x++
        {
            if(e.getSource()==YourComboBoxArray[x])
            {
                 try
                 {
                   ArrayList <String> OptionsList = new ArrayList();
                   for(int i=0;i<YourComboBoxArray[x].getItemCount();i++)
                   {
                         OptionsList.add(TeamPlayercmbx[x].getItemAt(i).toString();
                   }
                   DefaultComboBoxModel DCMB = new DefaultComboBoxModel(OptionsList.toArray());
                   YourComboBoxArray[x+1].setModel(DCMB);
                   YourComboBoxArray[x+1].removeItem(YourComboBoxArray[x].getSelectedItem());
                 }
                 catch(Exception ex)
                 {
                     //Log your errors or whatever you want to do if it's the last ComboBox in the Array
                 }
            }
        }
    

    This assumes you have an action listener on each index of the Combo Box Array