仅显示列表中的标签

时间:2013-12-13 18:21:16

标签: java javafx javafx-2 javafx-8

我有一个显示在组合框中的对象:

private List<ListGroupsObj> listGroups;

    public static class ListGroupsObj
    {

        private int groupId;
        private String groupName;


        public static ListGroupsObj newInstance()
        {
            return new ListGroupsObj();
        }

        public ListGroupsObj()
        {
        }

        public ListGroupsObj groupId(int groupId)
        {
            this.groupId = groupId;
            return this;
        }

        public ListGroupsObj groupName(String groupName)
        {
            this.groupName = groupName;
            return this;
        }

        public int getGroupId()
        {
            return groupId;
        }

        public String getGroupName()
        {
            return groupName;
        }

    }

ListGroupsObj ob = ListGroupsObj.newInstance().groupId(12).groupName("Test");

我想将此列表显示在组合框中。

private final ObservableList<ListGroupsObj> listGroups
        = FXCollections.observableArrayList(
        .........    
        );

final ComboBox<ListGroupsObj> cCountry1 = new ComboBox<>();

        cCountry1.setItems(CountrycomboList);

        cCountry1.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ListGroupsObj>()
        {

            @Override
            public void changed(ObservableValue<? extends ListGroupsObj> arg0, ListGroupsObj arg1, ListGroupsObj arg2)
            {
                if (arg2 != null)
                {
                    System.out.println("Selected Group: " + arg2.name);
                }
            }
        });

        cCountry1.getSelectionModel().select(0);

问题是如何将对象的名称从对象显示到Combox?

1 个答案:

答案 0 :(得分:3)

使用自定义列表单元格,您需要为单元格工厂提供ComboBox和setButtonCell方法:

public static class ListGroupListCell extends ListCell<ListGroupsObj> {
    @Override
    public void updateItem(ListGroupsObj item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
        } else {
            setText(item.getGroupName());
        }
    }
});

// ...

cCountry1.setCellFactory(new Callback<ListView<ListGroupsObj>, ListCell<ListGroupsObj>>() {
    @Override
    public ListCell<ListGroupsObj> call (ListView<ListGroupsObj> list) {
        return new ListGroupListCell();
    }
});
cCountry1.setButtonCell(new ListGroupListCell());