0

我正在尝试加载 2 个组合框;第二个组合框必须在第一个组合更改后加载。我正在使用netbeans,我尝试了几次,但它不起作用......要加载的项目必须与第一个组合中选择的项目的例外相同。

    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]);
    }
4

1 回答 1

1

一种方法是覆盖setSelectedItem()DefaultComboBoxModel保留对 的引用otherTeamModel,并根据需要从 更新它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
    }
}
于 2013-03-07T22:24:52.723 回答