I want to use 3 comboboxes that have the same set of choices. Once one is chosen from one of the comboboxes, the choice is eliminated in the other ones or they all keep the same choices, but only one is allowed that certain choice at a time. So for the second option, if box one chose "yellow", and then box two chooses "yellow", box one is now waiting on a choice. I've tried a few things with using comboboxes, Jcomboboxes, and observablelists/observableitemlists and still couldn't figure it out. I thought maybe using a listener but was stumped there also.
I set up my code like this
ObservableList<String> c = FXCollections.observableArrayList("Blue", "Green", "Grey", "Red", "Black", "Yellow");
ComboBox col = new ComboBox(c);
ComboBox col2 = new ComboBox(c);
ComboBox col3 = new ComboBox(c);
Here is how the comboboxes all look
After some testing and revising of Sai Dandem's help, this is the final code for anyone following this post. His code mostly worked but there was an issue with null pointer exceptions and the code sometimes not clearing all the boxes as wanted.
col.getSelectionModel().selectedItemProperty().addListener((obs, old, val)-> {
if(col2.getSelectionModel().getSelectedItem() != null && col2.getSelectionModel().getSelectedItem().equals(val)) {
col2.setValue(null);
}
if(col3.getSelectionModel().getSelectedItem() != null && col3.getSelectionModel().getSelectedItem().equals(val)) {
col3.setValue(null);
}
});
col2.getSelectionModel().selectedItemProperty().addListener((obs, old, val)-> {
if(col.getSelectionModel().getSelectedItem() != null && col.getSelectionModel().getSelectedItem().equals(val)) {
col.setValue(null);
}
if(col3.getSelectionModel().getSelectedItem() != null && col3.getSelectionModel().getSelectedItem().equals(val)) {
col3.setValue(null);
}
});
col3.getSelectionModel().selectedItemProperty().addListener((obs, old, val)-> {
if(col.getSelectionModel().getSelectedItem() != null && col.getSelectionModel().getSelectedItem() != null && col.getSelectionModel().getSelectedItem().equals(val)) {
col.setValue(null);
}
if(col2.getSelectionModel().getSelectedItem() != null && col2.getSelectionModel().getSelectedItem().equals(val)) {
col2.setValue(null);
}
});
I have not tested the below code, but you can do it with something like this...
col.valueProperty().addListener((obs, old, val)->updateValue(val, col));
col2.valueProperty().addListener((obs,old,val)->updateValue(val,col2));
col3.valueProperty().addListener((obs,old,val)->updateValue(val,col3));
private void updateValue(String val, ComboBox combo){
Stream.of(col,col2,col3).forEach(c->{
if(c!=combo && c.getValue().equals(val){
c.setValue(null);
}
});
}