我正在尝试加载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]);
}
一种方法是在DefaultComboBoxModel
中覆盖setSelectedItem()
,并保持对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
}
}