pror21
pror21

Reputation: 119

How to populate a ChoiceBox with objects from a List

I wan't to populate a ChoiceBox from a List<Object>. My Object has a name field which i wan't to use that as the choice text. Of course i need to know which object the user has selected in order to pass the correct data.

FXML Controller:

public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
    UniversitiesService uniService = new UniversitiesServiceImpl();
    List<University> uniList = uniService.getUniversitiesList();
    //uniChoiceBox.setItems(); Need some guidance here
}

University Entity:

private String universityName;
private String universityURL;
private String[] universityDataNames;

//getters setters

Upvotes: 0

Views: 1448

Answers (1)

James_D
James_D

Reputation: 209724

Just do

uniChoiceBox.getItems().setAll(uniList);

If you need to configure the display (i.e. if the toString() method in University doesn't give the text you need), add a converter:

uniChoiceBox.setConverter(new StringConverter<University>() {
    @Override
    public String toString(University uni) {
        return uni.getUniversityName();
    }
    @Override
    // not used...
    public University fromString(String s) {
        return null ;
    }
});

Upvotes: 4

Related Questions