JavaFX:使用 Object 属性的 ComboBox [英] JavaFX: ComboBox using Object property

查看:23
本文介绍了JavaFX:使用 Object 属性的 ComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一堂课:

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

    public String getName() {
       return name;
    }
}

我有一个此类的 ArrayList ArrayListdummyList;

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

我可以创建一个带有对象名称属性作为选择选项的 JavaFX ComboBox 而不用创建一个新的 ArrayList 对象名称吗?

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

伪代码:

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.这可能吗?

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

推荐答案

您可以使用自定义 cellFactory 以适合您需要的方式显示项目:

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

这篇关于JavaFX:使用 Object 属性的 ComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆