Thambi Durai P
Thambi Durai P

Reputation: 50

How to align CENTER in Jface tableviewer column checkbox image?

I'm using checkbox image in Jface tableviewer column, I want to show the checkbox image in center of the table column. Please check the attached image and share your thoughts to resolve this issue. Thanks in advance,

Tableviewer sample image

customizedTableViewer = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION);
    customizedTable.setLinesVisible(true);
    customizedTable.setHeaderVisible(true);
    customizedTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

TableColumn refTemplateTblclmnColumn = new TableColumn(customizedTable, SWT.NONE);
    refTemplateTblclmnColumn.setWidth(180);
    refTemplateTblclmnColumn.setText(TextResources.TEMPLATE_COLUMN);

TableColumn hospitalTblclmnColumn = new TableColumn(customizedTable, SWT.NONE);    
// I have tried following code but it's not working.
    hospitalTblclmnColumn.setAlignment(SWT.CENTER);
    hospitalTblclmnColumn.setWidth(100);
    hospitalTblclmnColumn.setText(TextResources.EL_HSP_COLUMN);

TableColumn providerTblclmnColumn = new TableColumn(customizedTable, SWT.NONE);
    providerTblclmnColumn.setWidth(100);
    providerTblclmnColumn.setText(TextResources.EL_PROVIDER_COLUMN);

Upvotes: 1

Views: 1215

Answers (1)

greg-449
greg-449

Reputation: 111142

The SWT.CENTER style only centers the text. For normal label providers there is no way to get a centered image. You need to draw the column yourself using something based on OwnerDrawLabelProvider.

The best thing to do is use TableViewerColumn rather than TableColumn so that you can set a separate label provider for each column. The columns you want to have a centered image can use an owner draw label provider like this:

public abstract class CentredImageCellLabelProvider extends OwnerDrawLabelProvider
{
  public CentredImageCellLabelProvider()
  {
    super();
  }

  @Override
  protected void measure(Event event, Object element)
  {
    // No action
  }

  @Override
  protected void erase(Event event, Object element)
  {
    // Don't call super.erase() to suppress non-standard selection draw
  }

  @Override
  protected void paint(Event event, Object element)
  {
    TableItem item = (TableItem)event.item;

    Rectangle itemBounds = item.getBounds(event.index);

    GC gc = event.gc;

    Image image = getImage(element);

    Rectangle imageBounds = image.getBounds();

    int x = event.x + Math.max(0, (itemBounds.width - imageBounds.width) / 2);
    int y = event.y + Math.max(0, (itemBounds.height - imageBounds.height) / 2);

    gc.drawImage(image, x, y);
  }

  protected abstract Image getImage(Object element);
}

Upvotes: 2

Related Questions