您可以创建一个如
AirPort带班
ID和
name成员以及
ComboBox该显示这些对象:
ComboBox<AirPort>。
AirPort班级:
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; }}
从数据库中获取项目并创建
ComboBox:
// Fill the list from the DatabaseObservableList<AirPort> airports = FXCollections.observableArrayList();airports.addAll(new AirPort(0, "Heathrow"), new AirPort(1, "Frankfurt"), new AirPort(2, "NewYork"));ComboBox<AirPort> combo = new ComboBox<>();combo.setItems(airports);
最后要显示对象的名称,您可以使用例如
StringConverter:
combo.setConverter(new StringConverter<AirPort>() { @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); }});
然后,当值更改时,您将获得
AirPort包含所需ID的对象:
combo.valueProperty().addListener((obs, oldval, newval) -> { if(newval != null) System.out.println("Selected airport: " + newval.getName() + ". ID: " + newval.getID());});
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)