Java – swing JTable sorted by date

I want to sort jtables by date in a column, but only display dates in DD mm yyyy format So all entries are the same, but different in invisible seconds

I have a tablemodel that uses the following methods to get data:

@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];
}

This is my tablerowsorter. 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, I can't sort it because the strings are all the same When I use such a date object directly

I don't know how to display it in the correct format, but I can sort it

How can I achieve these two goals?

Solution

Do not convert a date object to a string Instead, they are used directly in the model It is recommended that formatting is not the responsibility of the model, but use tablecellrenderer

Allow getvalueat to return a date object

Modify the table model, override the getcolumnclass method, and return the approval class of the hidden column (such as date. Class)

By default, this table will format the date object for you

If the default tablecellrenderer does not match your preference, you can provide your own tablecellrenderer

For details, see how to use tables, with particular attention to using custom renderers

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>