Samstag, 19. Dezember 2015

Duplicate rows in SWT TableViewer

When working with SWT/JFace TableViewers problems occured with identical rows.

The following picture shows the TableViewer (left one). The input is a List<String>. The input contains 2 equal strings "Trenner" (marked red).


I implemented a delete button (red array, center). My first implementation used the viewer.getSelection() method to obtain the current selection. I iterated over the selected strings and removed them from the list and from the viewer.

List input = ...

IStructuredSelection sel = (IStructuredSelection) viewer.getSelection();

for (Iterator i=sel.iterator(); i.hasNext(); ) {
   String action = (String) i.next();
   input.remove(action);
   viewer.remove(action);
}

The code worked but failed when removing the second "Trenner" in the above scenario. The first "Trenner" was removed and the second remained in the TableViewer.

The reason is obvious: java.util.List.remove(Object o) and TableViewer.remove(Object o) both remove the first occurence of the specified object. So the first "Trenner" is removed.

As far as I see there is no way to do it with JFace. So I used SWT fallback:

List input = ...

int[] selection = viewer.getTable().getSelectionIndices();
    
if (selection.length > 0) {     
  for (int index: selection) {
     input.remove(index);
  }            

  // Refresh the viewer
  viewer.refresh();
}

The solution is to work with the getSelectionIndecies() of the SWT-Table. Iterate over the idicies and remove the objects from the java.util.List input.
After that call TableViewer.refresh() and you are done.


Keine Kommentare:

Kommentar veröffentlichen