ekjcfn3902039 ekjcfn3902039 - 21 days ago 7
Java Question

NatTable sorting with custom comparator

I was looking at the (509_SortHeaderLayer.java) example as a reference point.

I add a custom comparator directly to the SortedList as shown in the example below. However, when I click on columns in the debugger, my custom comparator never reaches a breakpoint I set in the first line of my compare() method.

If I add the comparator as an AbstractRegistryConfiguration it works as expected (the breakpoint is reached when I click on a column).

Why does setting the comparator in the SortedLists constructor not work as I expected? Some general code snippets are shown below:

public void setSortComparatorWorks() {
SortedList<T> sortedList = new SortedList<>(eventList, null);
init(sortedList);
getNatTable().addConfiguration(new AbstractRegistryConfiguration() {

@Override
public void configureRegistry(IConfigRegistry configRegistry) {
configRegistry.registerConfigAttribute(SortConfigAttributes.
SORT_COMPARATOR, new MyComparator<T>(),
DisplayMode.NORMAL);
}
});
getNatTable().configure();
}

public void setSortComparatorDoesntWork() {
SortedList<T> sortedList = new SortedList<>(eventList,
new MyComparator<T>);
init(sortedList);
getNatTable().configure();
}

private void init(SortedList sortedList){
this.bodyDataProvider = new ListDataProvider<>(sortedList,
columnPropertyAccessor);

this.bodyDataLayer = new DataLayer(this.bodyDataProvider);

this.bodyLayerStack = new DefaultBodyLayerStack(new
GlazedListsEventLayer<>(this.bodyDataLayer, eventList));

this.columnHeaderLayerStack = new
GlazedListsColumnHeaderLayerStack<>(
columnHeaderDataProvider, sortedList,
columnPropertyAccessor, configRegistry, this.bodyLayerStack);

this.sortHeaderLayer = new SortHeaderLayer<>(columnHeaderLayerStack,
new GlazedListsSortModel<T>(sortedList,
columnPropertyAccessor, configRegistry, bodyDataLayer),
false);

setChildLayer(GridRegion.COLUMN_HEADER, sortHeaderLayer, 0, 0);
setChildLayer(GridRegion.BODY, bodyLayerStack, 0, 1);

getNatTable().addConfiguration(new SingleClickSortConfiguration());
}

Answer

It does not work as you expect, because the internal function will replace any existing Comparator on the SortedList with a Comparator that is derived out of the ConfigRegistry and the current applied sort state.

BTW, interesting that you refer to _509_SortHeaderLayerExample while an example with GlazedLists is _602_GlazedListsSortingExample.