javaswingnumbersjtablerowsorter

Sorting integers with JTable's default column sorter?


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?


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.