aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Trouble with JTable sorting dates. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Trouble with JTable sorting dates." Watch "Trouble with JTable sorting dates." New topic
Author

Trouble with JTable sorting dates.

Jason Richard
Ranch Hand

Joined: Oct 05, 2007
Posts: 69
Hi good friends. I'm having trouble with my Jtable. I have a table that has two columns, file and date modified. The date format needs to be SimpleDateFormat("MM-dd-yyyy-HH:mm:ss")

These columns need to be sortable. I have no problem sorting on the file name side. Unfortunately, the date side won't auto sort correctly. (Most notable when the years are not the same).
I normally would just sort by the lastModifed value, but I can't find a way to have both correct sorting AND the little up and down arrows that tell you which direction you've been sorting. I can get one OR the other.

I want to
1) Have the arrows.
2) When clicking on the date column i want correct sorting.
3) The date needs to be displayed in the SimpleDateFormat("MM-dd-yyyy-HH:mm:ss")



If I remove the sortKeys.add(new RowSorter.SortKey(1, SortOrder.ASCENDING));,
I add my own custom sort to the data before i add it to the table, but no arrows.
If I add that line, then I get my arrows, but i can't get correct sorting.

Any thoughts?

Thanks!

Jason
Rob Camick
Ranch Hand

Joined: Jun 13, 2009
Posts: 2216
    
    7
Don't store the formatted String in your model.

You need to store a Date object in the model and override the getColumnClass(...) method of the JTable (or TableModel) to return Date.class, then sorting will work properly.

The date needs to be displayed in the SimpleDateFormat("MM-dd-yyyy-HH:mm:ss")


Then you need to use a custom renderer to format the Date.See Table Format Renderers for a simple class you can use to do this.
Jason Richard
Ranch Hand

Joined: Oct 05, 2007
Posts: 69
Thanks. When I sorted on date, I still ran into issues. I ended up still using the formatter, but I initially set the column to be lastModified. Then I did the converstion to date before i formatted. Thanks for the help!
 
 
subject: Trouble with JTable sorting dates.