JavaFX: ComboBox using Object property

2019-01-07 00:07发布

问题:

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?

回答1:

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


回答2:

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