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

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

问题描述

让我说我有一个班级:

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

    public String getName() {
       return name;
    }
}

我有一个这个类的ArrayList 的ArrayList<哑GT; dummyList;

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

我是否可以创建一个带有Object name属性作为选择选项的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?

(可选)理想情况下,当显示名称时,如果选择了某个选项, combo.getValue()应该返回所选Dummy的引用,而不仅仅是名称。这可能吗?

(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天全站免登陆