Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX: ComboBox using Object property

Lets say I have a class:

public class Dummy {
    private String name;
    private String someOtherProperty;

    public String getName() {
       return name;
    }
}

I have an ArrayList of this class ArrayList<Dummy> dummyList;

Can I create a JavaFX ComboBox with the Object name property as selection options without creating a new ArrayList<String> with the object names?

Pseudocode:

ObservableList<Dummy> dummyO = FXCollections.observableArrayList(dummyList);
final ComboBox combo = new ComboBox(dummyO); // -> here dummyO.name?

(Optional) Ideally, while the name should be displayed, when an option has been selected, the combo.getValue() should return me the reference of the selected Dummy and not only the name. Is that possible?

like image 463
sandboxj Avatar asked Dec 17 '16 17:12

sandboxj


1 Answers

You can use a custom cellFactory to display the items in a way that suits your needs:

ComboBox<Dummy> comboBox = ...

Callback<ListView<Dummy>, ListCell<Dummy>> factory = lv -> new ListCell<Dummy>() {

    @Override
    protected void updateItem(Dummy item, boolean empty) {
        super.updateItem(item, empty);
        setText(empty ? "" : item.getName());
    }

};

comboBox.setCellFactory(factory);
comboBox.setButtonCell(factory.call(null));
like image 155
fabian Avatar answered Sep 28 '22 18:09

fabian