Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing JTable sort by Date

I would like to sort a Jtable by the date in one column, but only display the date in the format dd-MM-yyyy. So all entries are the same and only differ in the seconds which are not visible.

I have a TableModel which gets the data with the following method:

@Override
public Object getValueAt(int row, int col) {

    Object[][] tableData = new Object[rowDataMap.keySet().size()][1];
    int index = 0;
    for (Long key : pane.nqm_messages.keySet())
    {
        Date date = rowDataMap.get(key);

        SimpleDateFormat form = new SimpleDateFormat("dd-MM-yyyy"); 
        String outputDate = form.format(date);

        tableData[index][0] = outputDate;

        index++;
    }
    return tableData[row][col];
}

And here is my TableRowSorter where I want to sort the rows:

TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
List<SortKey> keys = new ArrayList<SortKey>();

SortKey sortKey;
sorter.setComparator( 0, new Comparator<String>() {  
    @Override
    public int compare(String s1, String s2)  {
        //Sort dd-MM-yyyy 
    }
});

If I do it like that I cant sort it because the strings are obv. all the same. When I directly use the date object like that

tableData[index][0] = date

I do not know how to display it in the correct format but the sorting can be done.

How can I achieve both?

like image 948
user1703554 Avatar asked Jun 24 '13 09:06

user1703554


2 Answers

Don't convert the Date objects to String. Instead, use them directly within the model. It's not the models responsibility to suggest formatting, instead use a TableCellRenderer.

Allow getValueAt to return the Date object.

Modify the table model and override the getColumnClass method and return the approiate class for the hiven columns (like Date.class).

The table, will by default, format the Date objects for you.

You can supply your own TableCellRenderer if the default one is not to your liking.

See How to use tables for more details, pay special attention to Using Custom Renderers

like image 197
MadProgrammer Avatar answered Nov 19 '22 09:11

MadProgrammer


Whenever the display and inner logic differs you should consider a TableModel and a CellRenderer. Why don't you add a CellRenderer on the date column? The cell renderer renders the date object using the SimpleDateFormat, however the inner values remain as Date objects. That way the sorting should work correctly, because the sorter works on the inner values.

like image 3
Oliver Watkins Avatar answered Nov 19 '22 08:11

Oliver Watkins