Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...