Stefan S.
Stefan S.

Reputation: 4103

How To Define Table's Vertical Alignment

Incredible easy question: I have a SWT table (viewer) and use a SWT.MeasureItem listener to set the cell height. How do I align the cell content to the bottom of the cell?

(It would probably work with another listener to SWT.PaintItem and some math and rendering all my cells manually, but that can't be the right way.)

public class TableDialog extends Dialog {

    public static void main(String[] args) {
        TableDialog dialog = new TableDialog(new Shell());
        dialog.open();
    }

    public TableDialog(Shell parent) {
        super(parent);
    }

    @Override
    protected void configureShell(Shell newShell) {
        super.configureShell(newShell);
        newShell.setText("Table Test");
        newShell.setSize(500, 300);
    }

    @Override
    protected Control createDialogArea(Composite parent) {
        Composite container = (Composite) super.createDialogArea(parent);
        container.setLayout(new FillLayout());

        TableViewer viewer = new TableViewer(container, SWT.BORDER | SWT.FULL_SELECTION);
        viewer.setContentProvider(new ArrayContentProvider());
        viewer.setInput(Arrays.asList("A", "B", " C"));

        Table table = viewer.getTable();
        table.setLinesVisible(true);
        table.addListener(SWT.MeasureItem, e -> e.height = 90);

        return container;
    }
}

Upvotes: 0

Views: 184

Answers (2)

greg-449
greg-449

Reputation: 111142

Once you start using SWT.MeasureItem you need to do the drawing as well.

Since you are using TableViewer you can combine all this in one class by using an OwnerDrawLabelProvider as the viewer label provider. A very simple version would be something like this:

viewer.setLabelProvider(new OwnerDrawLabelProvider()
  {
    @Override
    protected void paint(final Event event, final Object element)
    {
      String text = element.toString();

      GC gc = event.gc;

      int textHeight = gc.textExtent(text).y;

      int yPos = event.y + event.height - textHeight;

      gc.drawText(text, event.x, yPos);
    }


    @Override
    protected void measure(final Event event, final Object element)
    {
      event.height = 90;
    }


    @Override
    protected void erase(final Event event, final Object element)
    {
      // Stop the default draw of the foreground
      event.detail &= ~SWT.FOREGROUND;
    }
  });

Upvotes: 2

Rüdiger Herrmann
Rüdiger Herrmann

Reputation: 20985

I am afraid, SWT.PaintItem is the right way in this case.

One of the SWT Snippets demonstrates how to draw multiple lines in a table item. It may serve as a starting point for your custom drawing code:

http://git.eclipse.org/c/platform/eclipse.platform.swt.git/tree/examples/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet231.java

The Custom Drawing Table and Tree Items article provides further information.

Upvotes: 1

Related Questions