Swing JTable sort by date

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

I have a TableModel that receives 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 this, I cannot sort it, because the strings are obv. all the same. When I directly use a date object like this

tableData [index] [0] = date

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

How can I reach both?

+4
source share
2 answers

Do not convert Date objects to String . Instead, use them directly in the model. It is not the model's responsibility to suggest formatting, use TableCellRenderer .

Allow getValueAt return a Date object.

Modify the table model and override the getColumnClass method and return the matching class for hiven columns (e.g. Date.class ).

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

You can specify your own TableCellRenderer if the default is uncomfortable.

For more details, see How to use tables , pay special attention to Using custom renders.

+5
source

Whenever the logic of display and inner is different, you should consider TableModel and CellRenderer . Why aren't you adding CellRenderer to the date column? The cell renderer displays the date object using SimpleDateFormat, however the internal values ​​remain as Date objects. Thus, sorting should work correctly, because the sorter works with internal values.

+3
source

Source: https://habr.com/ru/post/1487846/


All Articles