Combo-box select item in JavaFX 2
I think the simplest solution is to write an autoSelect function that finds the matching CountryObj in your ObservableList. Once you find the correct CountryObj, tell the combobox to set that as its value. It should looks something like this...
private void autoSelectCountry(String countryCode)
{
for (CountryObj countryObj : countryComboList)
{
if (countryObj.getTCountryCode().equals(countryCode))
{
cbCountry1.setValue(countryObj);
}
}
}
EDIT:
This can be further refactored to reusable method for all ComboBox'es
that take different type parameter:
public static <T> void autoSelectComboBoxValue(ComboBox<T> comboBox, String value, Func<T, String> f) {
for (T t : comboBox.getItems()) {
if (f.compare(t, value)) {
comboBox.setValue(t);
}
}
}
where Func
is an interface:
public interface Func<T, V> {
boolean compare(T t, V v);
}
How to apply this method:
autoSelectComboBoxValue(comboBox, "Germany", (cmbProp, val) -> cmbProp.getNameOfCountry().equals(val));
comboBox.getSelectionModel().select(indexOfItem);
or
comboBox.setValue("item1");
Couple of months old question but here is more elegant solution for such type of problems.
Modify the CountryObj
class and override the hashCode
and equals
functions as below:
public class CountryObj {
private String TCountryDescr;
private String TCountryCode;
public CountryObj(String CountryDescr,String CountryCode) {
this.TCountryDescr = CountryDescr;
this.TCountryCode = CountryCode;
}
public String getTCountryCode() {
return TCountryCode;
}
public void setTCountryCode(String fComp) {
TCountryCode= fComp;
}
public String getTCountryDescr() {
return TCountryDescr;
}
public void setCountryDescr(String fdescr) {
TCountryDescr = fdescr;
}
@Override
public String toString() {
return TCountryDescr;
}
@Override
public int hashCode() {
int hash = 0;
hash += (TCountryCode != null ? TCountryCode.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
String otherTCountryCode = "";
if (object instanceof Country) {
otherTCountryCode = ((Country)object).TCountryCode;
} else if(object instanceof String){
otherTCountryCode = (String)object;
} else {
return false;
}
if ((this.TCountryCode == null && otherTCountryCode != null) || (this.TCountryCode != null && !this.TCountryCode.equals(otherTCountryCode))) {
return false;
}
return true;
}
}
Now in you code if you will execute the following statement, it will automatically select "Germany" for you.
cmbCountry.getSelectionModel().select("DE")
You can also pass an object of CountryObj to select
method above.