JavaFX ComboBox - Display text but return ID on selection

后端 未结 2 1433
北海茫月
北海茫月 2021-02-06 06:32

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

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-06 06:47

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

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


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

提交回复
热议问题