Nattable横向滚动时自定义DisplayConverter出现列偏移问题
Nattable横向滚动时DisplayConverter列偏移问题解决
问题现象
在Nattable中为特定列配置了自定义DisplayConverter:第2、7列需将长整型值转为十六进制字符串显示,第3、8列保持默认数字格式。但横向滚动表格后,转换器出现偏移:原十六进制列变为数字格式,原数字列反而显示十六进制。
问题原因
核心问题在于依赖列索引注册列标签。原代码通过pnames.indexOf()获取模型列索引,再调用ColumnLabelAccumulator.registerColumnOverrides绑定标签。当横向滚动(尤其是开启虚拟滚动时),视图层的列位置与模型层的列索引会产生错位,导致标签被错误绑定到滚动后的视图列上,最终引发转换器偏移。
解决方案
放弃列索引绑定,改为基于列的唯一数据属性键(即ILinkerMapConstants中定义的属性名)来动态分配标签。通过自定义ColumnLabelAccumulator,根据单元格对应的属性键返回对应标签,确保视图滚动或列排序时,标签始终关联到正确的数据列。
修改后的代码实现
1. 自定义ColumnLabelAccumulator
class PropertyBasedColumnLabelAccumulator extends DefaultColumnLabelAccumulator { private final List<String> propertyNames; public PropertyBasedColumnLabelAccumulator(List<String> propertyNames) { this.propertyNames = propertyNames; } @Override public void accumulateConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) { // 获取当前列对应的属性键 String propertyKey = this.propertyNames.get(columnPosition); // 根据属性键添加对应格式标签 if (ILinkerMapConstants.PROP_KEY_SECTION_SIZE.equals(propertyKey) || ILinkerMapConstants.PROP_KEY_OBJECT_SIZE.equals(propertyKey)) { configLabels.addLabel(NUMBER_FORMAT); } else if (ILinkerMapConstants.PROP_KEY_SECTION_ADDRESS.equals(propertyKey) || ILinkerMapConstants.PROP_KEY_OBJECT_MODULE_ADDRESS.equals(propertyKey)) { configLabels.addLabel(HEX_FORMAT); } // 保留默认列索引标签(按需选择) super.accumulateConfigLabels(configLabels, columnPosition, rowPosition); } }
2. 替换原标签注册逻辑
// 替换原ColumnLabelAccumulator实例 PropertyBasedColumnLabelAccumulator columnLabelAccumulator = new PropertyBasedColumnLabelAccumulator(pnames); columnHeaderDataLayer.setConfigLabelAccumulator(columnLabelAccumulator); // 转换器注册逻辑保持不变 configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, new DefaultLongDisplayConverter(), DisplayMode.NORMAL, NUMBER_FORMAT); configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, new LinkerMapHexAddressDisplayConverter(), DisplayMode.NORMAL, HEX_FORMAT);
注意事项
- 确保
pnames列表的顺序与表格模型中列的属性顺序完全一致,这样才能正确映射列位置到对应的属性键。 - 如果不需要默认的列索引标签,可以去掉
super.accumulateConfigLabels(...)调用,减少不必要的标签生成。
内容的提问来源于stack exchange,提问作者Sridhar Kumar
相关产品推荐
相关产品推荐

