tags:

views:

336

answers:

2

I am having trouble displaying Dates 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?

+2  A: 

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);
Peter Lang
have a read herehttp://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer
objects
+2  A: 

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.

camickr
+1, I don't think you are missing something. This approach is better than mine.
Peter Lang