I have a SQLite database with a date stored as VARCHAR
(yyyy-mm-dd), for example '2013-01-25'
.
My query retrieves the records from the table and displays it as stored. I need to display the VARCHAR
data in my JTable
as 'Friday January 25, 2013'. I suspect using setCellRenderer for the column containing the VARCHAR is the way to go. Further, I think it will be a two step process: first, converting the VARCHAR to a date value then formatting the date as desired. I can do so as follows if I grab the VARCHAR value from the JTable
and display it in a JTextField
:
MyDate = new SimpleDateFormat("yyyy-MM-dd").parse(rs.getString("My_Date"));
and then formatting it as desired
MyDateStr = new SimpleDateFormat("EEEE MMMM d, yyyy").format(MyDate);
That's all well and good; however, I need the formatted display in the JTable
column. I've never used setCellRenderer
, so I could use some help getting started.
Post by Rob Camick
about Table Format Renderers may solve your problem.
UPDATE:
I tried an example (as I am also curious to look DateFormat
in JTable which I have not done so far) using mKorbel code. The format which I have given as input
is "2013-01-25"
.
import java.awt.Dimension;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class JTableDateFormat {
public static void main(String[] args) {
Object[][] data = {
{"Amar", "2013-01-25"},
{"Sammy", "2013-01-25"}
};
Object[] columnNames = {"Name", "Date"};
JTable table = new JTable(data, columnNames);
table.getColumnModel().getColumn(1).setCellRenderer(new DateRenderer());
JFrame frame = new JFrame();
frame.add(new JScrollPane(table));
frame.setSize(new Dimension(400, 100));
frame.setVisible(true);
}
}
class DateRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
private Date dateValue;
private SimpleDateFormat sdfNewValue = new SimpleDateFormat("EE MMM dd hh:mm:ss z yyyy");
private String valueToString = "";
@Override
public void setValue(Object value) {
if ((value != null)) {
String stringFormat = value.toString();
try {
dateValue = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH).parse(stringFormat);
} catch (ParseException e) {
e.printStackTrace();
}
valueToString = sdfNewValue.format(dateValue);
value = valueToString;
}
super.setValue(value);
}
}