Friday, April 19, 2013

Creating SWT table


                    SWT TableViewer

Below I will try to explain you as to how to create a SWT table .
1.Set the layout on the composite over which you wanna create the Table specifying width and height etc .

2. Create a table
         TableViewer tableViewer = new TableViewer(parentComposite,SWT.BORDER );

3.Set the content provider
          tableViewer.setContentProvider(new TableContentProvider())
here TableContentProvider is implemeting IStructuredContentProvider
its method : public Object[] getElements(Object inputElement)
 Returns the elements in the input, which must be either an array or a Collection
So what ever you set as Input in the table we must convert it into array of objects here .

4. Set the LabelProvider  :tableViewer.setLabelProvider(new tableLabelprovider())
         tableLabelprovider    implements ITableLabelProvider
Here we can override two methods
  public String getColumnText(Object element, int columnIndex) : Returns the label text for the given column of the given element.
 Get the model which you setting in the table as input from element and using switch case we can return the value for each column according to the column Index
this is to set the label for each field in your table

5.Add columns according to your requirement

6. If you want any kind of cellEditor eg:TextCellEditor ,CheckboxCellEditor,Dialog cellEditor ,then you have  to add CellEditors for each column . If you want your column to be editable then we can use TextCellEditor .
7. set a cellModifier to your table viewer .
here in the method canModify we have to return true if for a particular column you want it to be editable .
in the method getValue() return value from your model according to the column (property name )
in the method modify() get the value from the table that has been modified and set it to your model and save the model accordingly .
Remember to refresh your table viewer .




No comments: