JTable setCellRenderer to format a textbox to date?
I have a SQLite database with a date stored as VARCHAR
(yyyy-mm-dd) for example '2013-01-25'
. My query fetches records from a table and displays them as saved. I need to display the data VARCHAR
in mine JTable
as "Friday 25th January 2013". I suspect that using setCellRenderer on a column containing a VARCHAR is the way to go. Also, I think it will be a two step process, firstly converting the VARCHAR to a date value and then formatting the date as desired. I can do it this way if I take the VARCHAR value from JTable
and display it in JTextField
:
MyDate = new SimpleDateFormat("yyyy-MM-dd").parse(rs.getString("My_Date"));
and then formatting as desired
MyDateStr = new SimpleDateFormat("EEEE MMMM d, yyyy").format(MyDate);
This is all good and good; however I need a formatted display in a column JTable
. I've never used setCellRenderer
, so I could use some startup help.
source to share
The post Rob Camick
about Format Table Editor might solve your problem.
UPDATE:
I tried an example (as I'm curious to look DateFormat
at in a JTable, which I haven't done yet) using mKorbel . The format I gave 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);
}
}
source to share
Make a class like this ...
public class DateRenderer extends DefaultTableCellRenderer {
public DateRenderer() { // This is a contructor
DateFormatter formatter = new DateFormatter("yyyy-MM-dd");
}
public class DateFormatter extends SimpleDateFormat { //This another class within a class
public DateFormatter(String pattern) {
super(pattern);
}
}
}
And add this to your panel -> jTable.setDefaultRenderer (Date.class, new DateRenderer ());
source to share