Search code examples
javaswtjfacenebulanattable

Icons in NatTable cells


I'm in process of replacing JFace TableViewer with NatTable. In my implementation with TableViewer I have images in cells, and I have implementation of ILabelProvider which is aware of how to get image for concrete state of object at runtime. So I call ILabelProvider.getImage(element) from ColumnLabelProvider.

In NatTable I know the way to add an image via registring configAttribute against configLabel. And for configAttribute I should explicitly tell what image to use. Surely I can create label for every state, register image for every label and use ConfigLabelAccumulator to tie it all togeather. But the amount of images is quite huge, and moreover I don't want to duplicate this logic. So is there more appropriate way for such a case? Just delegating to existing ILabelProvider?


Solution

  • In cases where you have quite some dynamic for retrieving the Image the label solution is insufficient (e.g. when thinking about a shop system with different images per row object). In such cases you typically implement a custom ImagePainter and implement the code the determine the Image to use in the getImage() method.

    The following snippet can be used as a starting point where you only need to implement your custom logic to determine the Image to use. This way you only need to register one ImagePainter. In NatTable this is also done for some static images like for example the TreeImagePainter.

    public class ContentDependentImagePainter<T> extends ImagePainter {
    
        IRowDataProvider<T> dataProvider;
    
        public ContentDependentImagePainter(IRowDataProvider<T> dataProvider) {
            this.dataProvider = dataProvider;
        }
    
        @Override
        protected Image getImage(ILayerCell cell, IConfigRegistry configRegistry) {
            // get the row object
            T rowObject = dataProvider.getRowObject(cell.getRowIndex());
            Image result = null;
    
            // perform your custom logic to determine the Image
    
            return result;
        }
    }