Cannot get sort function to work correctly in JTable in Java application

46 Views Asked by At

I'm trying to get integer values to sort correctly in a JTable.

Currently, the output looks like this:

99
989
983
98

However, I expect the output to be:

989
983
99
98 

Here is an image of my JTable:

JTable image

Here is my code:

private void populateTable(String[][] dataArray, String[] columnNames) {
        DefaultTableModel tableModel = new DefaultTableModel(dataArray, columnNames) {
            @Override
            public Class getColumnClass(int columnIndex) {
                if (columnIndex == 0) {
                    return Object.class;
                } else {
                    return Integer.class;
                }
            }

        };

        tableStatistics.setAutoCreateRowSorter(true);
        tableStatistics.setModel(tableModel);

        System.out.println(tableStatistics.getColumnClass(2));

    }

I have looked at forums and people say that overriding getCustomClass to specify column data type will solve the problem, however it has not.

I want the integer values to be sorted correctly.

I can confirm the getColumnClass override has successfully changed the data format but the sort still doesn't work.

Question

How do I go about getting the JTable to be able to sort this way?

0

There are 0 best solutions below