I have a JTable with a custom JTableModel, now I want to create a custom comparator, so the user can order the all column with my custom method.
I have this code:
ColumnListener
public class ColumnListener extends MouseAdapter {
    protected JTable table;
    public ColumnListener(JTable t) {
        table = t;
    }
    public void mouseClicked(MouseEvent e) {
        TableColumnModel colModel = table.getColumnModel();
        int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
        int modelIndex = colModel.getColumn(columnModelIndex)
        .getModelIndex();
        if (modelIndex < 0)
            return;
        if (sortCol == modelIndex)
            isSortAsc = !isSortAsc;
        else
            sortCol = modelIndex;
        for (int i = 0; i < columnsCount; i++) { 
            TableColumn column = colModel.getColumn(i);
            column.setHeaderValue(getColumnName(column.getModelIndex()));
        }
        table.getTableHeader().repaint();
        Collections.sort(v,new MyComparator(isSortAsc,columnModelIndex));
        table.tableChanged(new TableModelEvent(MyTableModelSpese.this));
        table.repaint();
    }
}
MyComparator
class MyComparator implements Comparator {
    protected boolean isSortAsc;
    protected Integer numeroColonna;
    public MyComparator( boolean sortAsc,Integer numberColumn) {
        isSortAsc = sortAsc;
        numeroColonna = numberColumn;
    }
    public int compare(Object o1, Object o2) {
        if (!(o1 instanceof NotaSpese) || !(o2 instanceof NotaSpese))
            return 0;
        NotaSpese s1 = (NotaSpese) o1;
        NotaSpese s2 = (NotaSpese) o2;
        int result = 0;
        if(numeroColonna==1){
            //ordinamento per data
            result = s1.getDataOperazioneData().compareTo(s2.getDataOperazioneData());
        }
        if (!isSortAsc)
            result = -result;
        return result;
    }
    public boolean equals(Object obj) {
        if (obj instanceof MyComparator) {
            MyComparator compObj = (MyComparator) obj;
            return compObj.isSortAsc == isSortAsc;
        }
        return false;
    }
}
When I try to order a column, Data (column ==1) and I see the collection after the order
Collections.sort(v,new MyComparator(isSortAsc,columnModelIndex));
the order of the object in collection v is ok. But if I see the element in the table are not ordered by my method. I see this data
2015-01-31
2015-12-30
2014-12-28
How can I fixed it?
 
                        
I think you can avoid using a custom
MouseAdapterif you use aTableRowSorterYou could also parametarize your Comparator, so you don't have to cast to
NotaSpese