Sarah
Sarah

Reputation: 145

SWT Table column offset/padding

I have an SWT Table with multiple columns. In this example, let's say there are three columns. The cells of each column all contain an image followed by some text (example pictured below). However, as you can see there is no spacing between the 2 - 3 column lines and their cells.

Is there a built-in way to add a buffer zone to those cells so the icons don't appear right on the edge line? Such as an offset property of some kind? I don't see any property overtly listed in either Table or TableColumn.

If not, is there a workaround beyond just adding white space to the cell images?

Please let me know if there's anything I can do to make my question clearer.

Table:

table

Upvotes: 0

Views: 1009

Answers (1)

Rüdiger Herrmann
Rüdiger Herrmann

Reputation: 21025

I don't think there is a designated way to adjust the margin and spacing of image and text within a cell. Apart from adding transparent pixels to the image (as you already suggested), you can use a PaintListener to gain control over how a cell is rendered.

The example below draws image and text with adjustable margin and spacing:

Listener paintListener = new Listener() {
  int leftMargin = 40;
  int rightMargin = 10;
  int imageSpacing = 200;
  @Override
  public void handleEvent( Event event ) {
    TableItem item = ( TableItem )event.item;
    Rectangle imageBounds = image.getBounds();
    Point textExtent = event.gc.textExtent( item.getText() );
    switch( event.type ) {
      case SWT.MeasureItem: {
        event.width += leftMargin + imageBounds.width + imageSpacing + textExtent.x + rightMargin;
        event.height = Math.max( event.height, imageBounds.height + 2 );
        event.height = Math.max( event.height, textExtent.y + 2 );
        break;
      }
      case SWT.PaintItem: {
        int x = event.x + leftMargin;
        int imageOffset = ( event.height - imageBounds.height ) / 2;
        event.gc.drawImage( image, x, event.y + imageOffset );
        x += imageSpacing;
        int textOffset = ( event.height - textExtent.y ) / 2;
        event.gc.drawText( item.getText(), x, event.y + textOffset );
        break;
      }
      case SWT.EraseItem: {
        event.detail &= ~SWT.FOREGROUND;
      }
    }
  }
};
table.addListener( SWT.MeasureItem, paintListener );
table.addListener( SWT.PaintItem, paintListener );
table.addListener( SWT.EraseItem, paintListener );

For a more thorough understanding of owner-drawn items in SWT please read the Custom Drawing Table and Tree Items article.

If you are using a JFace TableViewer, there is also an OwnerDrawLabelProvider as shown in this example: http://www.vogella.com/tutorials/EclipseJFaceTableAdvanced/article.html#styledcelllabelprovider-and-ownerdrawlabelprovider

Upvotes: 2

Related Questions