sandboxj
sandboxj

Reputation: 1254

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?

Upvotes: 7

Views: 9013

Answers (2)

fabian
fabian

Reputation: 82451

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

Upvotes: 13

Roberto Attias
Roberto Attias

Reputation: 1903

I'm assuming the ComboBox you're referring to is this: http://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ComboBoxBase.html. As getValue() is public, you can do:

public class MyComboBox<T> extends ComboBox<T> {
  private final Dummy dummy;
  public MyComboBox(Dummy dummy) {
    this.dummy = dummy;
  }
  public T getValue() {
    return dummy.getName();
  }
}

Upvotes: 0

Related Questions