Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Date in Jtable/ResultSet

Tags:

java

date

jtable

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?

like image 768
twodayslate Avatar asked Mar 09 '10 19:03

twodayslate


2 Answers

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);
like image 194
Peter Lang Avatar answered Oct 12 '22 14:10

Peter Lang


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.

like image 20
camickr Avatar answered Oct 12 '22 15:10

camickr