I have a Database table with airports, each airport has a name and an ID.
In JavaFX I have a form, with a ComboBox
, the combobox needs to display all the ai
You can create e.g. an AirPort
class with ID
and name
members and a ComboBox
that displays these objects: ComboBox
.
AirPort
class:
public class AirPort {
private int ID;
private String name;
public AirPort(int id, String name) {
this.ID = id;
this.name = name;
}
public int getID() { return ID; }
public String getName() { return name; }
}
Get the items from the DB and create the ComboBox
:
// Fill the list from the DataBase
ObservableList airports = FXCollections.observableArrayList();
airports.addAll(new AirPort(0, "Heathrow"),
new AirPort(1, "Frankfurt"),
new AirPort(2, "NewYork"));
ComboBox combo = new ComboBox<>();
combo.setItems(airports);
Finally to display the name of the objects you can use for example a StringConverter
:
combo.setConverter(new StringConverter() {
@Override
public String toString(AirPort object) {
return object.getName();
}
@Override
public AirPort fromString(String string) {
return combo.getItems().stream().filter(ap ->
ap.getName().equals(string)).findFirst().orElse(null);
}
});
And then when the value is changing you get back AirPort
objects which contains the needed ID:
combo.valueProperty().addListener((obs, oldval, newval) -> {
if(newval != null)
System.out.println("Selected airport: " + newval.getName()
+ ". ID: " + newval.getID());
});