1
votes

I have created a TableViewer with two columns and I want to add rows to it after pushing a button called "add". After pushing the button I want to create an empty row which first column cell will give the option to type text and the second column cell will give the option to browse in the system directories to select a folder.

I have managed to add an empty row after clicking the "add" button, but it returns the following error: An error has occurred. See error log for more details. assertion failed: Column 0 has no label provider. The purpose of the tableviewer is to insert a String variable in the first column cell and a path in the second column cell. With the data inserted by the user I want to create a List of a class called ProjectDirectory (this class has two String attributes).

I have also managed to remove the rows I select with the mouse and this works fine.

I am newbie using Jface and SWT, and I can´t get the way to do this. Can anyone help me please?

Code:

    Composite tableComposite = new Composite(pluginPathCreatedComposite, SWT.NONE);
    FormData tableCompositeData = new FormData();
    tableCompositeData.left = new FormAttachment(selectProjectPathLabel, 0, SWT.LEFT);
    tableCompositeData.top = new FormAttachment(selectProjectPathLabel, 40, SWT.TOP);
    tableCompositeData.right = new FormAttachment(selectProjectPathButton,-10,SWT.LEFT);
    tableCompositeData.bottom = new FormAttachment(createProjectConfigButton,-10,SWT.TOP);
    tableComposite.setLayoutData(tableCompositeData);

    //Create the tableviewer
    tableViewer = new TableViewer(tableComposite, SWT.SINGLE | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
    Table table = tableViewer.getTable();
    tableViewer.getTable().setLinesVisible(true);
    tableViewer.getTable().setHeaderVisible(true);
    tableViewer.setColumnProperties(COLUMN_HEADINGS);

    //Create the tableViewer columns
    TableViewerColumn variable = new TableViewerColumn(tableViewer, SWT.NONE);
    variable.getColumn().setText(COLUMN_HEADINGS[0]);
    variable.getColumn().setResizable(false);

    TableViewerColumn path = new TableViewerColumn(tableViewer, SWT.NONE);
    path.getColumn().setText(COLUMN_HEADINGS[1]);
    path.getColumn().setResizable(false);

    TableColumnLayout tableLayout = new TableColumnLayout();
    tableComposite.setLayout(tableLayout);

    //Set the columns proportions
    tableLayout.setColumnData(path.getColumn(), new ColumnWeightData(50));
    tableLayout.setColumnData(variable.getColumn(), new ColumnWeightData(50));

    //Set the first row as TextCell (this doesn´t work)
    CellEditor[] editors = new CellEditor[2];
    editors[0] = new TextCellEditor(tableViewer.getTable());
    editors[1] = new TextCellEditor(tableViewer.getTable());
    tableViewer.setCellEditors(editors);

    //Add button
    Button addRow = new Button(pluginPathCreatedComposite, SWT.NONE);
    FormData addRowData = new FormData();
    addRowData.top = new FormAttachment(tableComposite,0,SWT.TOP);
    addRowData.left = new FormAttachment(selectProjectPathButton,0,SWT.LEFT);
    addRowData.right = new FormAttachment(selectProjectPathButton,0,SWT.RIGHT);
    addRow.setLayoutData(addRowData);
    addRow.setText("Add");

    addRow.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {


            ProjectDirectory directory = new ProjectDirectory("A", "A");
            Table table = tableViewer.getTable();
            tableViewer.add(directory);
            table.setTopIndex(table.getItemCount());
            table.select(table.getItemCount() - 1);
        }
    });

    //Delete row
    Button deleteRow = new Button(pluginPathCreatedComposite, SWT.NONE);
    FormData deleteRowData = new FormData();
    deleteRowData.top = new FormAttachment(addRow,5,SWT.BOTTOM);
    deleteRowData.left = new FormAttachment(selectProjectPathButton,0,SWT.LEFT);
    deleteRowData.right = new FormAttachment(selectProjectPathButton,0,SWT.RIGHT);
    deleteRow.setLayoutData(deleteRowData);
    deleteRow.setText("Delete");

    deleteRow.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            ISelection selection = tableViewer.getSelection();
            if (selection instanceof IStructuredSelection) {
                Iterator iterator = ((IStructuredSelection) selection).iterator();
                while (iterator.hasNext()) {
                    Object obj = iterator.next();
                    tableViewer.remove(obj);
                }
            }
        }
    });

Image:

UI

EDIT:

I have created a content provider to take the ProjectDirectories of a List created in the code (I will change this in the future). After that, I have created a label provider for each column and it displays the data like I want.

The fact is that I want to add a new row in the table after pushing the add button and I want to make the first cell be a TextCellEditor (the second one will have an event to open the directory path of the system as the image one, but before doing this I also want to make it TextCellEditor). I have defined that the two columns will be like TextCell editor, and after pushing the add button I have managed to add an empty row, but I can´t get to type text in them. I have also created a setCellModifier to update the tableviewer. What am I doing wrong?

Code

    Composite tableComposite = new Composite(pluginPathCreatedComposite, SWT.NONE);
    FormData tableCompositeData = new FormData();
    tableCompositeData.left = new FormAttachment(selectProjectPathLabel, 0, SWT.LEFT);
    tableCompositeData.top = new FormAttachment(selectProjectPathLabel, 40, SWT.TOP);
    tableCompositeData.right = new FormAttachment(selectProjectPathButton,-10,SWT.LEFT);
    tableCompositeData.bottom = new FormAttachment(createProjectConfigButton,-10,SWT.TOP);
    tableComposite.setLayoutData(tableCompositeData);

    tableViewer = new TableViewer(tableComposite, SWT.SINGLE | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
    table = tableViewer.getTable();
    table.setLinesVisible(true);
    table.setHeaderVisible(true);
    tableViewer.setColumnProperties(COLUMN_HEADINGS);

    //Content provider
    tableViewer.setContentProvider(new ProjectConfigTableContentProvider());

    /*I have tried to use this instead of setting the label providers in the column definitions*/
   //tableViewer.setLabelProvider(new ProjectConfigTableLabelProvider());

    //Label provider setted in each column
    TableViewerColumn variable = new TableViewerColumn(tableViewer, SWT.NONE);
    variable.getColumn().setText(COLUMN_HEADINGS[0]);
    variable.getColumn().setResizable(false);
    variable.setLabelProvider(new ColumnLabelProvider(){
        public String getText(Object element) {
            if(element instanceof ProjectDirectory && element != null)
                return ((ProjectDirectory)element).getName();
            return super.getText(element);
        }
    });

    TableViewerColumn path = new TableViewerColumn(tableViewer, SWT.NONE);
    path.getColumn().setText(COLUMN_HEADINGS[1]);
    path.getColumn().setResizable(false);
    path.setLabelProvider(new ColumnLabelProvider(){
        public String getText(Object element) {
            if(element instanceof ProjectDirectory && element != null)
                return ((ProjectDirectory)element).getPath();
            return super.getText(element);
        }
    });

    //List created in code (will change this in the future)
    List<ProjectDirectory> b = new ArrayList<ProjectDirectory>();
    b.add(new ProjectDirectory("AA", "FF"));
    b.add(new ProjectDirectory("BB", "CC"));

    Project pro = new Project("A", "B", 2, b);

    //Input setted
    tableViewer.setInput(pro);

    TableColumnLayout tableLayout = new TableColumnLayout();
    tableComposite.setLayout(tableLayout);

    tableLayout.setColumnData(path.getColumn(), new ColumnWeightData(50));
    tableLayout.setColumnData(variable.getColumn(), new ColumnWeightData(50));

    CellEditor[] editors = new CellEditor[2];
    editors[0] = new TextCellEditor(table);
    editors[1] = new TextCellEditor(table);
    tableViewer.setCellEditors(editors);
    tableViewer.setCellModifier(new ProjectConfigTableCellModifier(COLUMN_HEADINGS,tableViewer));

    //addrow button
    Button addRow = new Button(pluginPathCreatedComposite, SWT.NONE);
    FormData addRowData = new FormData();
    addRowData.top = new FormAttachment(tableComposite,0,SWT.TOP);
    addRowData.left = new FormAttachment(selectProjectPathButton,0,SWT.LEFT);
    addRowData.right = new FormAttachment(selectProjectPathButton,0,SWT.RIGHT);
    addRow.setLayoutData(addRowData);
    addRow.setText("Add");

    addRow.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            ProjectDirectory directory = new ProjectDirectory("", "");
            tableViewer.add(directory);
            table.setTopIndex(table.getItemCount());
            table.select(table.getItemCount() - 1);
            tableViewer.editElement(directory, 0);
        }
    });

I also have created a labelProvider class to avoid setting the labels providers in each column like I have done, but it doesn´t work. The code is this:

@Override
    public String getColumnText(Object element, int columnIndex) {
    // TODO Auto-generated method stub
    ProjectDirectory projectDirectory = (ProjectDirectory) element;

    switch (columnIndex) {
    case 0:
        return projectDirectory.getName();
    case 1:
        return projectDirectory.getPath();
    }
    return null;
}

And the call to the class is like this:

tableViewer.setLabelProvider(new ProjectConfigTableLabelProvider());

Why does only work setting the label providers to the column and this way doen´t work?

2
Well you don't seem to have set label providers for anything - you need to do this. You also don't seem to have set a content provider or called setInput on the viewer, this is also required. To add / remove things you update the 'model' data in the content provider and then tell the viewer about these changes. - greg-449
@greg-449 Hi, I have edited the code with the advise you gave me. I have tried to set the columns label providers directly in the column definition or with a class, and only works the first way. I can´t understand why the second way doesn´t work. I have also tried to set the cells to be TextCellEditor but I can´t get it. After clicking the row cell it doen´t give the opcion to write. - Jaime
Using separate column label providers and using TableViewerColumn.setEditingSupport to set an editing support class for each column is the recommended way to do tables these days. - greg-449
Ok, I will try to do in that way, but more or less I have managed to make it work. What I don't understand is why my cells don't have TextCellEditor shape, any idea? - Jaime
A cell switches to the cell editor when you click on it. - greg-449

2 Answers

2
votes

Ok, I have found the solution to my problem.

First of all I have created a composite that will contain the table inside a bigger composite.

     private Composite createPluginPathCreatedComposite(){

        .................................

        //Label of bigger composite
        Text selectProjectPathText = new Text(pluginPathCreatedComposite, SWT.BORDER);
        selectProjectPathText.setEnabled(false);
        FormData selectProjectPathTextData = new FormData();
        selectProjectPathTextData.top = new FormAttachment(selectProjectPathLabel, 0, SWT.CENTER);
        selectProjectPathTextData.left = new FormAttachment(selectProjectPathLabel, 5,SWT.RIGHT);
        selectProjectPathTextData.right = new FormAttachment(100,-55);
        selectProjectPathText.setLayoutData(selectProjectPathTextData); 

        //Button to select a system directory
        Button selectProjectPathButton = new Button(pluginPathCreatedComposite, SWT.NONE);
        selectProjectPathButton.setText("Browse");
        FormData selectProjectPathButtonData = new FormData();
        selectProjectPathButtonData.top = new FormAttachment(selectProjectPathText, 0, SWT.TOP);
        selectProjectPathButtonData.left = new FormAttachment(selectProjectPathText, 5, SWT.RIGHT);
        selectProjectPathButtonData.right = new FormAttachment(100,-5);
        selectProjectPathButton.setLayoutData(selectProjectPathButtonData); 
        selectProjectPathButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                DirectoryDialog dialog = new DirectoryDialog(Display.getCurrent().getActiveShell());
                dialog.setFilterPath(""); // Windows specific
                selectProjectPathText.setText(dialog.open());
            }
        });

        //Create a composite for the table inside a bigger composite pluginPathCreatedComposite
        Composite tableComposite = new Composite(pluginPathCreatedComposite, SWT.NONE);
        FormData tableCompositeData = new FormData();
        tableCompositeData.left = new FormAttachment(selectProjectPathLabel, 0, SWT.LEFT);
        tableCompositeData.top = new FormAttachment(selectProjectPathLabel, 40, SWT.TOP);
        tableCompositeData.right = new FormAttachment(selectProjectPathButton,-10,SWT.LEFT);
        tableCompositeData.bottom = new FormAttachment(createProjectConfigButton,-10,SWT.TOP);
        tableComposite.setLayoutData(tableCompositeData);

        //Function to create the table. 
        createTable(tableComposite,selectProjectPathText);

        //add row to the tableviewer
        addRow.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                ProjectDirectory directory = new ProjectDirectory("Insert variable", "Click to add path");
                projectCompositeViewer.add(directory);
            }
        });

        //deleterow from the tableviewer
        Button deleteRow = new Button(pluginPathCreatedComposite, SWT.NONE);
        FormData deleteRowData = new FormData();
        deleteRowData.top = new FormAttachment(addRow,5,SWT.BOTTOM);
        deleteRowData.left = new FormAttachment(selectProjectPathButton,0,SWT.LEFT);
        deleteRowData.right = new FormAttachment(selectProjectPathButton,0,SWT.RIGHT);
        deleteRow.setLayoutData(deleteRowData);
        deleteRow.setText("Delete");

        deleteRow.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                ISelection selection = projectCompositeViewer.getSelection();
                if (selection instanceof IStructuredSelection) {
                    Iterator iterator = ((IStructuredSelection) selection).iterator();
                    while (iterator.hasNext()) {
                        Object obj = iterator.next();
                        projectCompositeViewer.remove(obj);
                    }
                }
            }
        });
        }

Create table function, I have passed the table Composite and the path of the project´s folder as parameter:

    private void createTable(Composite tableComposite, Text selectProjectPathText){
        //Create the tableViewer and it´s columns
        projectCompositeViewer = new ProjectConfigViewer(tableComposite, selectProjectPathText,SWT.SINGLE | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);

        //Create an input to display
        List<ProjectDirectory> b = new ArrayList<ProjectDirectory>();
        b.add(new ProjectDirectory("AA", "FF"));
        b.add(new ProjectDirectory("BB", "CC"));

        Project pro = new Project("A", "B", 2, b);
        projectCompositeViewer.setInput(pro);
    }

ProjectConfigViewer code:

public class ProjectConfigViewer extends TableViewer{

    public ProjectConfigViewer(Composite parent, Text selectProjectPathText,int style) 
    {
        super(parent, style);
        Table table = getTable();
        createColumns(parent, selectProjectPathText);
        table.setHeaderVisible(true);
        table.setLinesVisible(true);

        //Specify Content provider
        setContentProvider(new ProjectConfigTableContentProvider());
    }

    //Create the columns, column´s label providers and editingsuport to specify how will each column cell be: text column, dialog column...
    private void createColumns(Composite parent,Text selectProjectPathText)
    {   
        String[] COLUMN_HEADINGS = {"Variable", "Path"};

        TableColumnLayout tableLayout = new TableColumnLayout();
        parent.setLayout(tableLayout);

        //Specify first column labelprovider and create it 
        TableViewerColumn variable = createTableViewerColumn(COLUMN_HEADINGS[0], 0);
        variable.getColumn().setResizable(false);
        variable.setLabelProvider(new ColumnLabelProvider(){
            public String getText(Object element) {
                if(element instanceof ProjectDirectory && element != null)
                    return ((ProjectDirectory)element).getName();
                return super.getText(element);
            }
        });

         //Specify second column labelprovider and create it
        TableViewerColumn path = createTableViewerColumn(COLUMN_HEADINGS[1], 1);
        path.getColumn().setResizable(false);
        path.setLabelProvider(new ColumnLabelProvider(){
            public String getText(Object element) {
                if(element instanceof ProjectDirectory && element != null)
                    return ((ProjectDirectory)element).getPath();
                return super.getText(element);
            }
        });

        //Spedify the dimensions of each column
        tableLayout.setColumnData(path.getColumn(), new ColumnWeightData(50));
        tableLayout.setColumnData(variable.getColumn(), new ColumnWeightData(50));

        //Specify setEditingSupport for each cell. First cell will be text, second will be a Dialog.
        variable.setEditingSupport(new ProjectConfigVariableEditingSupport(this));
        path.setEditingSupport(new ProjectConfigPathEditingSupport(this, selectProjectPathText));
    }

    //Create tableviewercolumns
    private TableViewerColumn createTableViewerColumn(String header, int idx) 
    {
        TableViewerColumn column = new TableViewerColumn(this, SWT.LEFT, idx);
        column.getColumn().setText(header);
        column.getColumn().setResizable(true);
        column.getColumn().setMoveable(true);

        return column;
    }
}

Content provider:

public class ProjectConfigTableContentProvider implements IStructuredContentProvider {
    private List<ProjectDirectory> projectEntitiesList;

    @Override
    public Object[] getElements(Object arg0) {
        // TODO Auto-generated method stub
        if (arg0 instanceof Project){
            Project project = (Project) arg0; 
            if (project != null && project.getProjectDirectoriesList() != null){
                initializeTableProjectConfig(project);
                return projectEntitiesList.toArray();
            }
        }
        projectEntitiesList = new ArrayList<ProjectDirectory>();
        return projectEntitiesList.toArray();
    }

    private void initializeTableProjectConfig(Project project){
        try {
            List<ProjectDirectory> listProjectDirectory = new ArrayList<ProjectDirectory>();
            for (ProjectDirectory projectDirectory : project.getProjectDirectoriesList()) {
                if (projectDirectory != null) 
                    listProjectDirectory.add(projectDirectory);
            }
            this.projectEntitiesList = listProjectDirectory;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

EditingSupport of first column:

public class ProjectConfigVariableEditingSupport extends EditingSupport {
    private TextCellEditor cellEditor;

    public ProjectConfigVariableEditingSupport(ColumnViewer viewer) {
        super(viewer);
        cellEditor = new TextCellEditor(((TableViewer)viewer).getTable());
    }
    protected CellEditor getCellEditor(Object element) {
        return cellEditor;
    }
    protected boolean canEdit(Object element) {
        return true;
    }
    protected Object getValue(Object element) {
        return ((ProjectDirectory) element).getName();
    }
    @Override
    protected void setValue(Object element, Object value) {
        ((ProjectDirectory) element).setName(String.valueOf(value));
        getViewer().update(element, null);
    }
}

Editng support of second column:

public class ProjectConfigPathEditingSupport extends EditingSupport{
    private DialogCellEditor  cellEditor;

    //Pass selecProjectPathText of the bigger composite to brose from that directory
    public ProjectConfigPathEditingSupport(ColumnViewer viewer, Text selectProjectPathText) {
        super(viewer);
        cellEditor = new DialogCellEditor(((TableViewer)viewer).getTable()) {
            @Override
            protected Object openDialogBox(Control cellEditorWindow) {
                // TODO Auto-generated method stub
                DirectoryDialog dialog = new DirectoryDialog(cellEditorWindow.getShell());
                dialog.setText("Browse");
                dialog.setFilterPath(selectProjectPathText.getText()); // Windows specific
                return  dialog.open();
            }
        };
    }
    protected CellEditor getCellEditor(Object element) {
        return cellEditor;
    }
    protected boolean canEdit(Object element) {
        return true;
    }
    protected Object getValue(Object element) {
        return ((ProjectDirectory) element).getPath();
    }
    protected void setValue(Object element, Object value) 
    {
        ((ProjectDirectory) element).setPath(String.valueOf(value));
        getViewer().update(element, null);
    }
}

Model classes:

public class Project {
    private String name;
    private String path;
    private Integer quantity;
    private List<ProjectDirectory> projectDirectoryList;

    //Constructor
    public Project(String name, String path, Integer quantity, List<ProjectDirectory> projectDirectoriesList) {
        super();
        this.name = name;
        this.path = path;
        this.quantity = quantity;
        this.projectDirectoryList = projectDirectoriesList;
    }
    //GETTERS AND SETTERS
}

public class ProjectDirectory {
    private String name;
    private String path;

    //Constructor
    public ProjectDirectory(String name, String path) {
        super();
        this.path = path;
        this.name = name;
    }

    //Getters & setters

Photos: Explanation of use

1
votes

One of the simplest causes of this problem is when the label provider is added BEFORE creating the columns. always see to it that the label provider is added afterwards!