Sorting rows by columns in JTable

前端 未结 2 1774
夕颜
夕颜 2020-11-29 13:43

When you click the column header on my JTable, its sorts the rows alphabetically. This works for all of my columns except for one. In this column the values are all Strings,

2条回答
  •  情歌与酒
    2020-11-29 14:29

    The default row sorter will sort based on the column class. If the column class is Object (the default) then it uses the toString() method. If you can change what you put into the column to something that implements the Comparable interface (e.g. Integer/Double) then it will use that comparator instead. You will have to also change the column class on the table model.

    In order to do that you will have to extend DefaultTableModel (or implement AbstractTableModel or TableModel) and override the getColumnClass() method.

    If you can't change the data that goes into the column (for some reason you want to store strings there) then you will have to modify the RowSorter for the table.

    DefaultRowSorter rowSorter = new DefaultRowSorter();
    rowSorter.setComparator(numberColumnIndex,numberSortingComparator);
    table.setRowSorter(rowSorter);
    

提交回复
热议问题