I have a JTable and have added sorting. Now the JTable has 5 columns and the 2nd column in a date field converted to DD/MM/YYYY and displayed in a JTextField in the cell.
You need to implement comparator that treats date string as Date
rather simple String
have a look here
Because java.util.Date
implements Comparable<Date>
, it should be sufficient to let your TableModel
return Date.class
from getColumnClass()
for column two. Use a Custom Renderer to format the date as desired.
Addendum: Here's an example using setDefaultRenderer()
.
import java.awt.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
/** @see http://stackoverflow.com/questions/4553448 */
public class TableDate extends JPanel {
private static final int INT_COL = 0;
private static final int DATE_COL = 1;
private final Calendar calendar = Calendar.getInstance();
private final CustomModel model = new CustomModel();
private final JTable table = new JTable(model);
public TableDate() {
super(new GridLayout(1, 0));
table.setAutoCreateRowSorter(true);
table.setDefaultRenderer(Date.class, new DateRenderer());
table.setPreferredScrollableViewportSize(new Dimension(320, 240));
JScrollPane sp = new JScrollPane(table);
this.add(sp);
for (int i = 1; i <= 20; i++) {
model.addRow(newRow(i));
}
}
private Object[] newRow(int i) {
calendar.add(Calendar.DAY_OF_YEAR, 1);
return new Object[]{Integer.valueOf(i), calendar.getTime()};
}
private static class CustomModel extends DefaultTableModel {
private final String[] columnNames = {"Index", "Date"};
@Override
public Class<?> getColumnClass(int col) {
if (col == INT_COL) {
return Integer.class;
} else if (col == DATE_COL) {
return Date.class;
}
return super.getColumnClass(col);
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
}
private static class DateRenderer extends DefaultTableCellRenderer {
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
public DateRenderer() {
super();
}
@Override
public void setValue(Object value) {
setText((value == null) ? "" : formatter.format(value));
}
}
private void display() {
JFrame f = new JFrame("TableDate");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new TableDate().display();
}
});
}
}