I have 9 (+ default) selectable options (all the same for the 20) for my JComboBoxes.
The 20 are part of 2 JComboBox array. (10-10 for each).
I want to limit them like this:
If there is 4 selected from (for example) option 4 and the user selects a 5th
one of it, one of them jumps back to default to keep the limit of 4.
How Can I do it ?
for ex:
for (int i = 0; i < roles1.length; i++) {
roles1[i] = new JComboBox();
roles1[i].setModel(new DefaultComboBoxModel(new String[] { "Not Selected", "PartnerInCrime", "Driver",
"Gunman", "Coordinator", "Hacker", "Distraction", "GadgetGuy", "Bruglar", "ConMan" }));
roles1[i].setBounds(boxPlace, 200, 100, 20);
boxPlace += 105;
getFrame().getContentPane().add(roles1[i]);
}
Here is a suggestion which is supposed to lead you in the right direction.
First of all, you have to add an ActionListener to each ComboBox, that calls a method which compares all selections with your current one.
roles1[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// get the current selection
JComboBox currentBox = (JComboBox)e.getSource();
String currentSelection = (String)currentBox.getSelectedItem();
// call the method and hand in your current selection
checkForSelectionExceeding(currentSelection);
}
});
In your scanning method you should memorize the amount of matches while scanning. If your limit is exceeded, reset the current box to default and stop scanning. Something like this:
private void checkForSelectionExceeding(String currentSelection){
int matches = 0;
for(int i=0; i<roles1.length; i++) {
if(roles1[i].getSelectedItem().equals(currentSelection)) {
matches++;
}
if(matches > 4) {
roles1[i].setSelectedItem("Not Selected");
break;
}
}
}
You only have to refactor this solution a little in order to scan both arrays sequentially.
Hope this helps.