javaswingjtabletablerowsorter

JTable RowSorter order wrong


I imported javax.swing.table.TableRowSorter;

used it in the table model. It works properly with Strings, but with numbers it orders everything in a weird way, as shown in the picture. I'm a noob at coding so I don't really know how to properly google for such an issue yet.

enter image description here

 DefaultTableModel model = new DefaultTableModel();
 table.setAutoCreateRowSorter(true);

Not sure if you still need more code. It is a mess tbh, as object oriented coding came up in school after i started this.


Solution

  • Your problem is that your sorting is doing an alphabetical sort, which works well for String objects, but once you have Integers to sort, you will have the situation that 2 > 19, because alphabetically 2 is after 1.

    You will need something like:

    DefaultTableModel model = new DefaultTableModel(data,columns) {
        @Override
        public Class getColumnClass(int column) {
            switch (column) {
                case 4: {
                    //assuming that the int column you have is in the fourth column
                    return Integer.class; 
                } break;
                default:
                    return String.class;
            }
        }
    };
    

    where data is an Object[][] and columns is an Object[].