Search code examples
javanattable

Dynamically change row foreground color of particular cell in NatTable


do you have nay suggestions to dynamically change the color of cell , I have tried below but when table does not have the those label ("FAILURE") even after that row will remains colored. I want to revert back the color of colored cell when FAILURE label is not present in the table.

private static final String FAILURE = "FAILURE";
void example(){
final DefaultBodyLayerStack bodyLayer = underlyingLayer.getBodyLayer();



        // Custom label "FAILURE" for cell
        IConfigLabelAccumulator cellLabelAccumulator = new IConfigLabelAccumulator() {
            Integer rowCount = null;

            @Override
            public void accumulateConfigLabels(LabelStack configLabels,
                    int columnPosition, int rowPosition) {
                int rowIndex = bodyLayer.getRowIndexByPosition(rowPosition);

                for (GridConsoleRow gridConsoleRow : underlyingLayer.getBodyDataProvider().getList()) {
                    if (StringUtils.equals(gridConsoleRow.getLogLevel().trim(), FAILURE)) {
                            rowCount = bodyLayer.getPreferredRowCount()-1;
                            break;
                        }
                    }

                    if (rowCount != null && rowIndex == rowCount.intValue()) {
                    configLabels.addLabel(FAILURE);
                    }
                }
            };
        bodyLayer.setConfigLabelAccumulator(cellLabelAccumulator);

        // Custom style for label "FAILURE"
        natTable.addConfiguration(new AbstractRegistryConfiguration() {
            @Override
            public void configureRegistry(IConfigRegistry configRegistry) {
                Style cellStyle = new Style();
                cellStyle.setAttributeValue(
                        CellStyleAttributes.FOREGROUND_COLOR,
                        GUIHelper.COLOR_RED);
                configRegistry.registerConfigAttribute(
                        CellConfigAttributes.CELL_STYLE, cellStyle,
                        DisplayMode.NORMAL, FAILURE);

            }
        });
    }

Solution

  • Have you debugged that the FAILURE label is really not present? NatTable only shows what it should, so if you registered the style with a red background only for the FAILURE label, it will only render rows in red that have that label. To be honest, I don't understand the logic of your IConfigLabelAccumulator. Probably the rowCount member is the cause, as you never set it back to null again if there is no failure. Not sure why you anyhow store that information in a member variable.