Question

I am working with a JTable that contains a few columns with different datatypes (int, string, date). When I run the app the data displays fine but if I use the column headers to sort the data it freezes on the columns that contain Date objects. Below is the code. Columns 8, 9, & 10 are the ones causing the problem. How do I make it so the Date columns are sortable?

public void updateLogTable() {

    DefaultTableModel model = (DefaultTableModel) logTable.getModel();
    List<LogObject> lstLogObjects = new ArrayList<LogObject>();
    lstLogObjects = LogManager.getLog();
    for (int i = 0; i < lstLogObjects.size(); i++) {
        Object[] temp = new Object[13];

        temp[0] = Integer.parseInt(lstLogObjects .get(i).getLogID());
        temp[1] = lstLogObjects .get(i).getLogType();
        temp[2] = lstLogObjects .get(i).getYear();
        temp[3] = lstLogObjects .get(i).getQuarter();
        temp[4] = lstLogObjects .get(i).getOriginalID();
        temp[5] = lstLogObjects .get(i).getSubject();
        temp[6] = lstLogObjects .get(i).getAction();
        temp[7] = lstLogObjects .get(i).getRequester();
        temp[8] = lstLogObjects .get(i).getADate(); //Returns java.util.Date
        temp[9] = lstLogObjects .get(i).getCDate(); //Returns java.util.Date
        temp[10] = lstLogObjects .get(i).getSDate(); //Returns java.util.Date
        temp[11] = lstLogObjects .get(i).getRemarks();
        temp[12] = lstLogObjects .get(i).getField1();

        model.addRow(temp);

    }
    model.fireTableDataChanged();
 }
Was it helpful?

Solution

Did you override the getColumnClass(...) method of your TableModel to return the proper class?

The table sort methods will then sort the column and treat it as a Date rather than invoke toString() on the Date object.

If you need more help then post your SSCCE demonstrating the problem.

OTHER TIPS

I would recommend using JXTable for anything less trivial than displaying two columns. Basic intro is for example here.

Other option is to use Long as element in table and use column renderer which would format date:

 temp[8] = lstLogObjects .get(i).getADate().getTime()

 table.getColumnModel().getColumn(8).setCellRenderer( new DefaultTableCellRenderer(){
    public Component getTableCellRendererComponent(JTable table, Object value,
                                        boolean isSelected, boolean hasFocus,
                                        int row, int column){
        Object value2 = value; 
        if(row>0 && column==8) //put your own condition here
             value2 = new Date((Long)value).toString(); //your own formatting here
        return super.getTableCellRendererComponent(table, value2,
                                          isSelected, hasFocus,
                                          row, column);
     }
  });
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top