swttableviewer

SWT - TableViewer - Refreshing Selection


I have a button that runs a method. The method gets the selected Rows in the table and adds them to an arraylist. This works well the first time executed. But if the user selected the wrong row, they will be able to re select a different row and add that selection data to the arraylist.

But with my current the code, it does not matter what row the user selects the second time the first selected data is always added to the arraylist. It is like the selection needs to be reset or refreshed before the user selects the new row.

Button Code

Button pdfButton = new Button(composite, SWT.PUSH);
   pdfButton.setText("Get Plotter List");
   pdfButton.setEnabled(true);
   pdfButton.addSelectionListener(new SelectionAdapter() {
       public void widgetSelected(SelectionEvent e) {
          getPlotterSelection();
       }
   }); 

Method Code

 public void getPlotterSelection() {
    selectedPlotters.clear(); <-- Clearing the ArrayList
    int[] row = viewer.getTable().getSelectionIndices(); <-- Getting Current Selections
    Arrays.sort(row);

    if (row.length > 0) {
       for(int i = row.length-1; i >= 0; i--){
          PrinterProfile pp = new PrinterProfile(aa.get(i).getPrinterName(), aa.get(i).getProfileName());
          selectedPlotters.add(pp);
        }
     }
     viewer.getTable().deselectAll();
   }

As I am writing this, I think maybe the problem is in the getSelectionIndices(). It seems to be getting the number of rows selected, but not the actual row number

Edit

The problem was in my logic. I was getting the correct Indices but using i varaible in the for loop to get the value.

for(int i = row.length-1; i >= 0; i--){
          PrinterProfile pp = new PrinterProfile(aa.get(i).getPrinterName(), aa.get(i).getProfileName());

changed it to

aa.get(row[i].getPrinterName(), etc...

and it works like I thought it would


Solution

  • Since you are already using a TableViewer, why not get the selection from it?

    IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
    YourObject[] array = (YourObject[])selection.toArray();
    

    Then you can iterate over the array and add them to your ArrayList.