I create an array of combo boxes in a for loop like so:
for(int i = 0; i < 5; i++) {
...
comboStudy[i] = new JComboBox(studyModel);
comboStudy[i].addActionListener(new studyListener());
comboStudy[i].setActionCommand("" + i);
...
}
The listener is an instance inner class:
public class studyListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
int i = Integer.parseInt(evt.getActionCommand());
// do some stuff that requires i and also access
// to the instance members of the containing class
}
}
The problem I now face is that whenever I make a selection at run time in comboStudy[0] the action event gets fired 5 times. The first time i is 4, decreasing each time until it gets to 0.
I also tried it using an ItemListener, but it has the same problem.
Please help!
This is because you are using the same
ComboBoxModelin all of your JComboBoxes.Each
JComboBoxis a listener of theComboxBoxModeland theComboBoxModelwill notify each listener whenever there is a change to the data model. When you select an item in aJComboBox, theComboBoxModelchanges which in turn fires events to eachJComboBox. This is why you see events occurring on eachJComboBox.