You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NatTable已配置选中行颜色,如何自定义符合条件的选中单元格样式

NatTable选中单元格自定义样式不生效问题解决

问题场景

我有一个NatTable,通过标签mylabel实现了部分行着色功能,mylabel通过ConfigLabelAccumulator进行赋值:

final AggregateConfigLabelAccumulator labelAccumulator = new AggregateConfigLabelAccumulator();
labelAccumulator.add(new ColumnLabelAccumulator());
labelAccumulator.add(new IConfigLabelAccumulator() {
    @Override
    public void accumulateConfigLabels(final LabelStack configLabels, final int columnPosition, final int rowPosition) {
        if (<my condition>) configLabels.addLabelOnTop("mylabel");
    }
});

mylabel的样式通过ConfigRegistry配置,未选中行背景色为黄色,选中行背景色为深黄色:

final ConfigRegistry configRegistry = new ConfigRegistry();
final Style style = new Style();
style.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, GUIHelper.COLOR_YELLOW);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, style, DisplayMode.NORMAL, "mylabel");

final Style styleSelected = new Style();
styleSelected.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, Display.getDefault().getSystemColor(SWT.COLOR_DARK_YELLOW));
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, styleSelected, DisplayMode.SELECT, "mylabel");

补充说明:当<my condition>对应的条件发生变化后,我会执行natTable.doCommand(new VisualRefreshCommand());来立即刷新表格。

以上配置整体运行正常,仅存在一个问题:选中状态下的单元格样式不符合预期。当<my condition>为true时,如何让对应的选中单元格使用自定义的样式?

示例说明:
两张截图中两行均处于选中状态(因此显示深黄色),仅选中锚点位置不同。
需自定义样式的单元格
包含529的单元格,选中时需要使用自定义样式。
需保持原有样式的单元格
包含/E0001的单元格,保持现有样式即可。

解决方法

通过调整SelectionLayer的DefaultSelectionLayerConfiguration和DefaultSelectionStyleConfiguration即可实现需求,代码如下:

this.selectionLayer = new SelectionLayer(glazedListsEventLayer, false);
this.selectionLayer.addConfiguration(new DefaultSelectionLayerConfiguration() {
    @Override
    protected void addSelectionStyleConfig() {
        final DefaultSelectionStyleConfiguration dssc = new DefaultSelectionStyleConfiguration();
        dssc.anchorBgColor = null;
        dssc.anchorFgColor = null;
        dssc.anchorBorderStyle = new BorderStyle(1, GUIHelper.COLOR_RED, LineStyleEnum.SOLID);
        addConfiguration(dssc);
    }
});

核心逻辑:NatTable默认会给选中锚点单元格强制应用内置的锚点背景、前景色,优先级高于自定义标签的样式。将anchorBgColor和anchorFgColor设置为null后,锚点单元格就会优先使用自定义标签的样式,仅保留红色边框来标识锚点位置,既满足了选中状态下的自定义着色需求,也能清晰区分选中锚点。


内容的提问来源于stack exchange,提问作者floh.mueller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:15:07