java JavaFX ComboBox - 显示文本但在选择时返回 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41634789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:00:34  来源:igfitidea点击:

JavaFX ComboBox - Display text but return ID on selection

javasqljavafxcombobox

提问by LTKort

I have a Database table with airports, each airport has a name and an ID.

我有一个包含机场的数据库表,每个机场都有一个名称和一个 ID。

In JavaFX I have a form, with a ComboBox, the combobox needs to display all the airport names and when the form is submitted it needs to insert the ID of the airport into the database (not its name).

在 JavaFX 中,我有一个带有 的表单,ComboBox组合框需要显示所有机场名称,并且在提交表单时,它需要将机场的 ID(而不是其名称)插入到数据库中。

But I'm not really figuring out what the solution is.

但我并没有真正弄清楚解决方案是什么。

I have a

我有一个

ObservableList vliegveldenList = FXCollections.observableArrayList();
ObservableList vliegveldenIDList = FXCollections.observableArrayList();

Database connection to fill the ComboBox

数据库连接填充 ComboBox

ResultSet rs = Project_Fasten_Your_Seatbelt.conn.createStatement()
 .executeQuery("SELECT vliegveldnaam, vliegveld_id FROM fys_project.vliegvelden;");
while (rs.next()) {
    vliegveldenList.add(rs.getString(1));
    vliegveldenIDList.add(rs.getString(2));
}

Fills the combobox:

填充组合框:

vliegveldHerkomst.setValue("Luchthaven ...");
vliegveldHerkomst.setItems(vliegveldenList); 

And this is added to the database when button is pressed:

当按下按钮时,这将添加到数据库中:

String registratieValue = registratieNmrTxt.getText();
String vluchtValue = vluchtNrmTxt.getText();
String vliegveldValue = (String) vliegveldHerkomst.getSelectionModel().getSelectedItem();
String bestemmingValue = (String) vliegveldBestemming.getSelectionModel().getSelectedItem(); 
String gevondenValue = (String) vliegveldGevonden.getSelectionModel().getSelectedItem();
LocalDate dGevondenValue = datumGevondenDate.getValue();
LocalDate dVluchtValue = datumVluchtDate.getValue();
String gewichtValue = gewichtBagageTxt.getText();
String kleurenValue = (String) kleuren.getSelectionModel().getSelectedItem();
String kofferValue = (String) kofferMerken.getSelectionModel().getSelectedItem();
String opmerkingValue = opmerkingArea.getText();

//Data gevonden bagage invoeren
Project_Fasten_Your_Seatbelt.conn.createStatement().executeUpdate(
        "INSERT INTO gevondenbagage "
        + "(registratienummer, datumgevonden, datumaangemeld, vliegveldherkomst, "
        + "vliegveldbestemming, vliegveldgevonden, vluchtnummer, vluchtdatum, gewicht, "
        + "kleur, merk, `speciale opmerkingen`, userid)"
        + "VALUES ('" + registratieValue + "','" + dGevondenValue + "','" + today.format(localDate) + "','"
        + vliegveldValue + "','" + bestemmingValue + "','" + gevondenValue + "','"
        + vluchtValue + "','" + dVluchtValue + "','" + gewichtValue + "','"
        + kleurenValue + "','" + kofferValue + "','" + opmerkingValue + "','"
        + Project_Fasten_Your_Seatbelt.getUserId() + "')");

This all works okay, but instead of the name of the airport I want to set the ID for the airport for vliegveldValue.

这一切正常,但我想设置机场的 ID 而不是机场的名称vliegveldValue

How do I do this?

我该怎么做呢?

回答by DVarga

You can create e.g. an AirPortclass with IDand namemembers and a ComboBoxthat displays these objects: ComboBox<AirPort>.

例如,您可以创建一个AirPort类,其中包含IDname成员以及ComboBox显示这些对象的 :ComboBox<AirPort>

AirPortclass:

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; }
}

Get the items from the DB and create the ComboBox:

从数据库中获取项目并创建ComboBox

// Fill the list from the DataBase
ObservableList<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);

Finally to display the name of the objects you can use for example a StringConverter:

最后显示您可以使用的对象的名称,例如 a 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);
    }
});

And then when the value is changing you get back AirPortobjects which contains the needed ID:

然后当值发生变化时,您会返回AirPort包含所需 ID 的对象:

combo.valueProperty().addListener((obs, oldval, newval) -> {
    if(newval != null)
        System.out.println("Selected airport: " + newval.getName() 
            + ". ID: " + newval.getID());
});

回答by Tayyab

Your Airport Class.. .

您的机场班级...

public class Airport {

private int id;
private String name;

public Airport(int id, String name) {
    super();
    this.id = id;
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}// class Airport

}//类机场

Create Observable list of Airport

创建机场的可观察列表

ObservableList<AirPort> airports = FXCollections.observableArrayList();
airports.add(new Airport(1, "Beijing Capital International Airport"));
airports.add(new Airport(2, "Los Angeles International Airport"));
airports.add(new Airport(3, "London Heathrow Airport"));

Set item of your combo box. .

设置组合框的项目。.

combo.setItems(airports);

After this when you run your program you get the output like this. .. enter image description here

在此之后,当你运行你的程序时,你会得到这样的输出。.. 在此处输入图片说明

To get name of Airports you have to need to override toString method in Airportclass.

要获取机场的名称,您必须在Airport类中覆盖 toString 方法。

@Override
public String toString() {
    return this.getName();
}

After this you will get output like.. . enter image description here

在此之后,您将获得类似...的输出。 在此处输入图片说明



Now to get the id of selected airport you can set an event handler. .

现在要获取所选机场的 id,您可以设置一个事件处理程序。.

private void setEventOnAirport() {
    combo.setOnKeyReleased(event -> {
        if (event.getCode().equals(KeyCode.ENTER)) {
            Airport airport = combo.getSelectionModel().getSelectedItem();
            System.out.println(airport.getId());
        }
    });
}

By this function you can see the IDof selected Airport. . .

通过此功能,您可以看到所选机场的ID。. .