Vaadin ListBox如何指定显示字段及ID存储字段
ListBox组件指定显示字段与存储ID的配置方案
实现思路
ListBox没有独立的setItemLabelGenerator方法,你可以通过替换默认文本渲染器自定义展示内容,ID值的存储可以根据业务场景选择两种实现方式:
方案一:保留实体作为组件泛型(推荐)
不用修改原有数据源结构,选中后直接从实体对象中取ID字段即可,代码改动最小:
ListBox<MyEntitySource> entityListBox = new ListBox<>(); List<MyEntitySource> entitySource = (List<MyEntitySource>) entityRepository.findAll(); // 自定义渲染逻辑,指定展示description字段 entityListBox.setTextRenderer(MyEntitySource::getDescription); entityListBox.setItems(entitySource); // 取值时直接从选中实体中获取ID entityListBox.addValueChangeListener(event -> { if (event.getValue() != null) { Long selectedId = event.getValue().getId(); // 后续业务逻辑处理 } });
方案二:组件直接绑定ID为值
如果需要getValue()直接返回ID字段,不需要二次提取,可以调整组件泛型为ID的类型:
// 泛型改为你ID字段的实际类型,比如Long ListBox<Long> entityListBox = new ListBox<>(); List<MyEntitySource> entitySource = (List<MyEntitySource>) entityRepository.findAll(); // 构建ID到description的映射关系 Map<Long, String> idToDesc = entitySource.stream() .collect(Collectors.toMap(MyEntitySource::getId, MyEntitySource::getDescription)); entityListBox.setItems(idToDesc.keySet()); // 指定渲染展示对应的description entityListBox.setTextRenderer(id -> idToDesc.get(id)); // 此时getValue直接返回选中的ID值 Long selectedId = entityListBox.getValue();
原理解释
ListBox默认的文本渲染器会调用元素对象的
toString()方法作为展示内容,所以你没做配置时会输出实体的toString格式内容,替换渲染器后即可自定义展示任意字段。
内容的提问来源于stack exchange,提问作者the Ben B
相关产品推荐
相关产品推荐

