I am having trouble displaying Date
s in the format I want in my JTable
. My JTable
has been created using a ResultSet and lists.
I tried the following in getValueAt(.)
but no luck:
if(value instanceof Date)
{
//System.out.println("isDate");
DateFormat formatter = DateFormat.getDateInstance();
SimpleDateFormat f = new SimpleDateFormat("MM/dd/yy");
value = f.format(value);
Date parsed = (Date) value;
try {
parsed = (Date) f.parse(value.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
value = parsed.toString();
}
The println(.)
is never printed so it isn't even getting to that. The Format that is being displayed is Apr 10, 1992
but I want 04/10/92
While we are on the topic of Date
in JTables
... I have isCellEditable(.)
as true but I cannot edit the Date cells. How do you do this?
Do not override getValue
, use a TableCellRenderer
instead:
TableCellRenderer tableCellRenderer = new DefaultTableCellRenderer() {
SimpleDateFormat f = new SimpleDateFormat("MM/dd/yy");
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if( value instanceof Date) {
value = f.format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
}
};
table.getColumnModel().getColumn(0).setCellRenderer(tableCellRenderer);
The Format that is being displayed is Apr 10, 1992
Sounds like a toString() representation of the Date is being stored in the TableModel and not a Date Object. So you need to check how your data is copied from the ResultSet to the TableModel. Make sure you are using the resultSet.getObject() method. Or maybe the problem is that you are storing a String in your database that is formatted the way you see it.
Anyway, once you are able to actually store a Date object in the TableModel, check out Table Format Renderers which allows you to create a custom renderer with a customized date format in a single line of code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With