Search code examples
javaswttableviewer

Refresh the TableViewer table every time add a new item to list


I created a TableViewer table to display data from an ArrayList. I want to refresh the table every time I add a new item to my list. But now the table waits until all my data has been added to the list then the table will display all the data at once. Can some one help me with this problem? I got stuck at here for a long time... Here is some code

private void buildPerformanceTable(
        IPerformanceDataRetriever performanceDataRetriever) {

    tableViewer.setContentProvider(new JobProfileContentProvider());
    tableViewer.setLabelProvider(new JobProfileLabelProvider());
    tableViewer.setComparator(new JobProfileViewerComparator());
    Table table = tableViewer.getTable();

    for (ColumnType columnType : ColumnType.values()) {
        buildTableColumn(columnType.getColumnName(),
                columnType.getColumnIndex());
    }

    tableViewer.setInput(performanceDataRetriever);

    for (int i = 0; i < table.getColumnCount(); i++) {
        table.getColumn(i).pack();
    }
    table.setHeaderVisible(true);
    table.setLinesVisible(true);
}


public class JobProfileContentProvider implements IStructuredContentProvider{

    private static final long SERIAL_VERSION_UID = 6452458171326245659L;



    /**
     * {@inheritDoc}
     */
    @Override
    public Object[] getElements(Object object) {
        return ((IPerformanceDataRetriever) object).providePerformanceData()
                .toArray();
    }

    /**
     * <b>This method is not implemented.</b> <br>
     * 
     * {@inheritDoc}
     */
    @Override
    public void dispose() {
    }

    /**
     * <b>This method is not implemented.</b> <br>
     * 
     * {@inheritDoc}
     */
    @Override
    public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
    }
}


public class JobProfileInfoMock implements IPerformanceDataRetriever {

    /**
     * Creates an instance of list containing active JobProfile.
     * 
     * @return List contains JobProfile.
     */
    public static List<JobProfile> getJobProfileWithAllActiveJobs(){
        List<JobProfile> JobProfiles = new ArrayList<JobProfile>();
        for(int i=1;i<=6;i++){
            JobProfile profile = new JobProfile.ProfileBuilder().jobId(i)
            .cpuUsage(80+i).memoryUsage(40+i).ipAddress("192.1.12.4"+i).isActive(true)
            .build();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        JobProfiles.add(profile);
        System.out.println(JobProfiles.size());
        }
        return JobProfiles;
    }
}

Solution

  • Call tableViewer.refresh() each time you add to the table.

    You must make one call to tableViewer.setInput before you can call refresh.

    If you are running in a background thread you must use Display.asyncExec to run the refresh call in the UI thread.