javaswingjide

Custom sorting of SortableTable


I fix project which uses jide SortableTable. If table contains data only in English, then sorting works just fine. In case data is in mixed western European languages, sorting fails.

If i sort the data collections using Collator with strength "SECONDARY" it works fine.

The question is: how to make the SortableTable to sort data with SECONDARY collator strength or with custom comparator?


Solution

  • JIDE's SortableTableModel uses ObjectComparatorManager to get the comparator. You can register your Collator (by default, we use PRIMARY collator)

    Collator collator = Collator.getInstance(); collator.setStrength(Collator.SECONDARY);

    ObjectComparatorManager.registerComparator(String.class, collator , new ComparatorContext("CollatorSecondary")); // "CollatorSecondary" could be any string that is unique in your app

    Then in your SortableTableModel subclass, you return new ComparatorContext("CollatorSecondary") by overriding getColumnComparatorContext(int column) for the column.

    Another quick way is to override SortableTableModel's getComparator(int column) if you just want this behavior in one table.

    Last but not least, you may also need to call SortableTableModel's setAlwaysUseComparators(true) because for the performance consideration, we used the cell value's compareTo method if available without using a comparator.