nattablenebula

NatTable - how to implement custom CopyDataToClipboardSerializer


in CopyDataToClipboardSerializer I need to override copiedCells variable.

I do use NatTableFactory.class where I create table, register new CopyDataCommandHandler, override table style and so on. But I do not know how to override CopyDataToClipboardSerializer. Or should I register new one and create own class?


Solution

  • I don't know your NatTableFactory class. So I am not sure what you are doing inside that class.

    If you need a custom serializer to for example replace line breaks in a text to a space to avoid breaking the table structure, you need to create a custom implementation and use that.

    class MyCopyDataCommandHandler extends CopyDataCommandHandler {
    
        public MyCopyDataCommandHandler(SelectionLayer selectionLayer, ILayer columnHeaderLayer, ILayer rowHeaderLayer) {
            super(selectionLayer, columnHeaderLayer, rowHeaderLayer);
        }
    
        @Override
        protected void internalDoCommand(CopyDataToClipboardCommand command, ILayerCell[][] assembledCopiedDataStructure) {
            ISerializer serializer = new MyCopyDataToClipboardSerializer(assembledCopiedDataStructure, command);
            serializer.serialize();
        }
    }
    
    class MyCopyDataToClipboardSerializer extends CopyDataToClipboardSerializer {
    
        public MyCopyDataToClipboardSerializer(ILayerCell[][] copiedCells, CopyDataToClipboardCommand command) {
            super(copiedCells, command);
        }
    
        @Override
        protected String getTextForCell(ILayerCell cell) {
            return super.getTextForCell(cell).replace('\n', ' ');
        }
    }
    

    Then register the custom MyCopyDataCommandHandler like this if the headers should be exported too:

    CopyDataCommandHandler copyHandler =
            new MyCopyDataCommandHandler(
                    selectionLayer,
                    columnHeaderDataLayer,
                    rowHeaderDataLayer);
    gridLayer.registerCommandHandler(copyHandler);