tags:

views:

56

answers:

2

How can I make my JTable show specific stuff for each column?

Can I use an Object for more than one column? I want to have a column showing the date (dd.mm.yyyy) and another to show the time (hh:mm) but as I have it now it only shows the String representation of the Date object as a whole.

public class AppointmentTableModel extends AbstractTableModel {
    ...
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return appointments.get(rowIndex).getByColumn(columnIndex);
    }
}

public class Appointment {
    ...
    public Object getByColumn(int columnIndex) {
        switch (columnIndex) {
            case 0: return date;
            case 1: return date;
            case 2: return sample;
            case 3: return sample;
            case 4: return history;
            case 5: return comment;
        }
        return null;
    }
}
+1  A: 

The only thing you have to change is your getByColumn.

You just have to apply two different formats for case 0 and case 1 for example.


You can use a SimpleDateFormat for this:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
// ...
case 0: return dateFormat.format(date);
case 1: return timeFormat.format(date);
Peter Lang
+3  A: 

You can set specific renderers for the two columns, one will take the Date object and format it as a date string, the other will take the Date object and format it as a time string.

See this tutorial for an example on Date rendering.

akf
+1: That's more elegant than my solution :)
Peter Lang