I have the following jtable jtable image I get the information from a database and everything is saved as string in the table, I just want to sort the second column "Fecha de recepcion" which has dates in the format dd-mm-yyyy, I used a row classifier but it takes the dates as strings.
I made a TableCellRenderer for just that column and applied the following properties
Table.getColumnModel().getColumn(1).setCellRenderer( new Render());
Table.setAutoCreateRowSorter(true);
but it still sorts it as string.
I would really appreciate if someone can guide me on what I'm doing wrong
This is my class that implements TableCellRenderer
public class Render implements TableCellRenderer{
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
LocalDate date = LocalDate.parse(value.toString(),formatter);
Component c = renderer.getTableCellRendererComponent(table,
date, isSelected, hasFocus, row, column);
return c;
}
}
The important thing here is the data, what's in the
TableModel, as this is what the table will use to sort by.Based on
LocalDate date = LocalDate.parse(value.toString(),formatter);it would appear that your data isStringbased, which will be the cause of you core problem.Instead, you data should be using
LocalDate.LocalDateis comparable by default, so you don't need any "special" comparators or additional support, it will "just work" out of the box, for example, unsorted, descending, ascending...