John Smith
John Smith

Reputation: 787

TableViewer Adding data from ArrayLists Eclipse plugin

I have the following code that creates a TableViewer.

TableViewer viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
Table table = viewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);

How to create a ContentProvider in order to add data from array lists in the columns of the table? I have these lists and I want to add them in the table.

Upvotes: 0

Views: 1166

Answers (1)

greg-449
greg-449

Reputation: 111217

You really need one object per row in the table.

If you create an array or ArrayList containing a single object per row you can use the standard ArrayContentProvider:

viewer.setContentProvider(ArrayContentProvider.getInstance());

The row data class might be something like:

class RowData
{
  private String [] cols;

  RowData(String [] theCols)
  {
    cols = theCols;
  }

  String getColumn(int index)
  { 
    return cols[index];
  }
}

Create a array of these from your existing lists:

RowData [] rows = new RowData [listSize];

for (int i = 0; i < listSize; i++)
 {
   rows[i] = new RowData(new String [] {col0List.get(i), col1list.get(i), ...});
 }

Set this as the input to the viewer:

 viewer.setInput(rows);

But only do this after setting the content provider and label provider in the viewer.

Use a label provider implementing ITableLabelProvider:

 class MyLabelProvider extends LabelProvider implements ITableLabelProvider
 {
   @Override
   public String getColumnText(Object element, int columnIndex)
   {
     RowData rowData = (RowData)element;

     return rowData.getColumn(columnIndex);
   }

   @Override
   public Image getColumnImage(Object element, int columnIndex)
   {
     return null;
   }
 }

Upvotes: 1

Related Questions