Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX ComboBox - Display text but return ID on selection

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 airport names and when the form is submitted it needs to insert the ID of the airport into the database (not its name).

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

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.

How do I do this?

like image 410
LTKort Avatar asked Jan 13 '17 12:01

LTKort


2 Answers

You can create e.g. an AirPort class with ID and name members and a ComboBox that displays these objects: ComboBox<AirPort>.

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<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:

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 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());
});
like image 174
DVarga Avatar answered Oct 18 '22 08:10

DVarga


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 Airport class.

@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. .

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 ID of selected Airport. . .

like image 28
Tayyab Avatar answered Oct 18 '22 07:10

Tayyab