Reputation: 545
I have a table that consists of three columns: Name | Date-Time | Description
The values for Date-Time are actually stored 2 separate fields in database table and (Outdated database - can't change, so have to work around it).
I have the following code applied:
tbNotes.setAutoCreateRowSorter(true); //tbNotes is the JTable
DefaultRowSorter sorter = ((DefaultRowSorter) tbNotes.getRowSorter());
ArrayList list = new ArrayList();
list.add(new RowSorter.SortKey(2, SortOrder.DESCENDING)); //column 2 because I have an invisible ID column
sorter.setSortKeys(list);
sorter.sort();
The result produced appears correct - the rows are sorted by date with older items appearing towards the bottom. However, sometimes I see this:
It is obvious that the sort looks at the first character in a string and assumes that 1 is bigger than 0 so 12/28/2011 is larger(newer) than 01/03/2012
How would I go about having a proper sort on my JTable by date?
Thank You
P.S. Here is the code for populating the JTable
try {
DefaultTableModel noteDataModel = new DefaultTableModel() {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
tbNotes.setModel(noteDataModel);
Object[] objects = new Object[4];
ListIterator<Todonote> todoNoteListIterator = noteList.listIterator();
while (todoNoteListIterator.hasNext()) {
todoNoteEntity = todoNoteListIterator.next();
DateFormat noteDateFormatter = new SimpleDateFormat("MM/dd/yyyy");
String noteDateTime = noteDateFormatter.format(todoNoteEntity.getUserDate())
+ " - " + todoNoteEntity.getUserTime().substring(0, 2) + ":" + todoNoteEntity.getUserTime().substring(2);
objects[0] = todoNoteEntity.getPrimaryKey();
objects[1] = todoNoteEntity.getUserContact().getName();
objects[2] = noteDateTime;
objects[3] = todoNoteEntity.getNotes();
noteDataModel.addRow(objects);
}
Edit 1
I updated the table model with
@Override
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
}
}
return Object.class;
}
It seems to work now, but dates are showing up as Oct 26, 2012 instead of yyyy/MM/dd - HH:mm - how would I fix that?
Upvotes: 1
Views: 435
Reputation: 216
I'm not sure, but if you want to display a Date object as appointed format like yyyy/MM/dd - HH:mm, why not try the Renderer?
Upvotes: 1