Question

I am currently using the following method on my JTable to get an automatic sort on the columns

table.setAutoCreateRowSorter(true);

This currently allows me to click each header and the corresponding column will sort for anything with letters. It is messing up when it tries to sort my columns that have integers. It appears to be sorting each digit at a time instead of sorting by the actual number. For example it will say 8 is larger than 100 since 8 is larger than 1. Is there some way I can override this behavior?

Was it helpful?

Solution

It is messing up when it tries to sort my columns that have integers

Probably because:

  1. You are storing the numbers as Strings, or
  2. You are storing the data as an Integer object but you didn't override the getColumnClass() method of your TableModel to return Integer.class for that column. The proper Comparator will only be used when your column class is correct.

See the section from the Swing tutorial on Concepts: Renderers and Editors for more information and an example of how you might override the getColumnClass() method.

OTHER TIPS

You probably need to set a row sorter with the specific comparator:

Comparator<Integer> comparator;
TableRowSorter sorter;
table.setRowSorter(sorter);
sorter.setModel(table.getModel());
sorter.setComparator(comparator);

Here can be found more about comparator and possible problems with it. But, @camickr is also right that if the column class is set correctly, for Integer should not normally be necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top