Why does my JTable sort an integer column incorrectly?

后端 未结 4 945
情深已故
情深已故 2020-12-01 21:02

I have a JTable that uses a DefaultTableModel and I allow for sorting when the user clicks on the column headers. However, when the user clicks on a header for a column that

4条回答
  •  臣服心动
    2020-12-01 21:41

    DefaultTableModel returns a column class of Object. As such all comparisons will be done using toString. This may be unnecessarily expensive. If the column only contains one type of value, such as an Integer, you should override getColumnClass and return the appropriate Class. This will dramatically increase the performance of this class.

    In this case you should add the snippet code below in your table model:

        @Override
    public Class getColumnClass(int columnIndex) {
        if (db.isEmpty()) {
            return Object.class;
        }
        return getValueAt(0, columnIndex).getClass();
    }
    

提交回复
热议问题