0

i am trying to load 2 combo Boxes; the secoond combo box has to be loaded after the change in the first combo. I am using netbeans and i tried several times but it does not work ... the items to be loaded have to be the same with the exceptio of the item chosen in the first combo.

    private void firstTeamComboBoxItemStateChanged(java.awt.event.ItemEvent evt)
{                                                   
        loadSecondTeamComboBox();
    }                                                  

    private void loadSecondTeamComboBox()
    {
        String[] theTeamsInTheLeague2 = league.loadTeamsInLeague(secondTeam.getLeague());
        secondTeamComboBox.addItem("Select a Team");
        for(int i = 0; i < theTeamsInTheLeague2.length; i++)
            if (!(theTeamsInLeague2[i].equals(firstTeam.getLeague()))
                secondTeamComboBox.addItem(theTeamsInTheLeague2[i]);
    }


    private void loadFirstTeamComboBox()
    {
        String[] theTeamsInTheLeague1 = league.loadTeamsInLeague(firstTeam.getLeague());
        firstTeamComboBox.addItem("Select a Team");
        for(int i = 0; i < theTeamsInTheLeague1.length; i++)
            firstTeamComboBox.addItem(theTeamsInTheLeague1[i]);
    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Alpan67
  • 105
  • 2
  • 5
  • 15
  • Well to be honest i do't undestand well what's happening in this related answer – Alpan67 Mar 05 '13 at 16:23
  • What exactly is not working? What are the results of your code? – Guido Mar 05 '13 at 16:29
  • The problem is that both, the firstTeamCombo and the secondTeamCombo load the same items and in the same moment ... i would like the secondteamCombo to be loaded after having chosen the item of the firstTeamCOmbo ... – Alpan67 Mar 05 '13 at 16:38
  • Yes, this is a different problem than the one addressed [here](http://stackoverflow.com/a/3191882/230513), but the solution uses the same idea of updating the opposite combo's model. – trashgod Mar 05 '13 at 16:43
  • Well i studied your example and now it is a little bit clearer (sorry but i am learning ...), but i have more than 20 items in the first Combo Box and i would like after having chosen the item to load the other 19 in the second combo – Alpan67 Mar 05 '13 at 16:53

1 Answers1

1

One approach would be to override setSelectedItem() in DefaultComboBoxModel and keep a reference to otherTeamModel, updating it as needed from allTeamsInTheLeague.

class MyComboBoxModel extends DefaultComboBoxModel {
    private DefaultComboBoxModel otherTeamModel;

    public MyComboBoxModel(DefaultComboBoxModel otherTeamModel) {
        this.otherTeamModel = otherTeamModel;
    }
    @Override
    public void setSelectedItem(Object item) {
        super.setSelectedItem(item);
        otherTeamModel.removeAllElements();
        // add all allTeamsInTheLeague except item
    }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045