如何在Jface tableviewer列复选框图像中对齐CENTER?

时间:2018-05-29 14:16:14

标签: java swt eclipse-rcp jface tableviewer

我在Jface tableviewer列中使用复选框图像,我想在表格列的中心显示复选框图像。请查看附件图片并分享您的想法以解决此问题。提前谢谢,

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);

1 个答案:

答案 0 :(得分:1)

SWT.CENTER样式仅使文本居中。对于普通标签提供商,无法获得居中的图像。您需要使用基于OwnerDrawLabelProvider的内容自行绘制列。

最好的办法是使用TableViewerColumn而不是TableColumn,以便为每列设置单独的标签提供程序。要拥有居中图像的列可以使用所有者绘制标签提供程序,如下所示:

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);
}