0

I'm trying to automatically select the first item in a filtered table.

I'm essentially doing the following:

table = new TableViewer(...);
table.addFilter(filter);
table.setContentProvider(contentProvider);
table.setInput(input);
first = table.getElementAt(0);
table.setSelection(new StructuredSelection(first));

The surprising thing is that (depending on the filter) I can get an element that is filtered out from getElementAt(0). The result is that ultimately, no item will be selected.

I have tried calling table.refresh() before getting the element with the same results.

If I call getElementAt(0) at a later point, I do indeed get the correct first element (that is not filtered out).

How can I make getElementAt respect the filtering immediately?

Balz Guenat
  • 1,242
  • 2
  • 10
  • 30
  • Have a look at [this](https://www.vogella.com/tutorials/EclipseJFaceTableAdvanced/article.html#jfacetable_filter) under heading "Filtering data 2.2" – Joel Apr 16 '19 at 07:49
  • @Joel Doesn't really help. As I said, I tried calling refresh() but still got the filtered item. – Balz Guenat Apr 16 '19 at 07:59
  • 1
    https://stackoverflow.com/questions/14464059/how-can-i-get-the-ordered-elements-of-a-jfaces-tableviewer check. apply the same logic. – Joel Apr 16 '19 at 08:00
  • try using table.getInput().get(0) – Abhishek Tiwari Apr 16 '19 at 10:09
  • If you feel an answer solved the problem, please mark it as 'accepted' by clicking the green checkmark. This helps keep the focus on older posts which still don't have answers. – Rüdiger Herrmann Apr 20 '19 at 05:32

2 Answers2

1

In my experience, the most reliable way to select the first (visible) element is - for once only - to bypass JFace, rely on its internal data model, and use SWT API to select the first TableItem like this:

static Object selectFirstElement(TableViewer tableViewer) {
  Object firstElement = null;
  Table table = tableViewer.getTable();
  if (table.getItemCount() > 0) {
    firstElement = table.getItem(0).getData();
    tableViewer.setSelection(new StructuredSelection(firstElement), true); // true == reveal
  }
  return firstElement;
}

I've been using this code successfully for several years with sorted, filtered, and virtual tables.

Rüdiger Herrmann
  • 18,905
  • 11
  • 53
  • 72
0

Well, I found what was wrong and it was my own fault. The filter I set is mutable so it can filter more or less strictly. The problem was that I activated the more strict filtering after I set the selection.

Thanks everyone for the help anyways.

Balz Guenat
  • 1,242
  • 2
  • 10
  • 30