Reputation: 1461
I'm getting data for the DB and displaying in a table.
My getColumnClass is
@Override
public Class<? extends Object> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
when I print the value, I get the class name as java.sql.Timestamp, but when it display I'm have a problem, it just display dd/MM/yyyy, but I need it to display dd/MM/yyyy HH:mm, how can I achieve this?
Apart from doing this, I need to check if the datatime is lesser than today then disable the row
Upvotes: 5
Views: 2155
Reputation: 76
I know this is a very old question, but I was having a very similar problem and decided to post a better solution for the problem.
First, you should define a new class: TimestampCellRenderer.java
package gui;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.swing.table.DefaultTableCellRenderer;
public class TimestampCellRenderer extends DefaultTableCellRenderer {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
public TimestampCellRenderer() {
super();
}
public void setValue(Object value) {
if (formatter == null) {
formatter = DateFormat.getDateInstance();
}
setText((value == null) ? "" : formatter.format(value));
}
}
And then in your GUI class, add this definition to your class:
yourTable.getColumnModel().getColumn(1).setCellRenderer(new TimestampCellRenderer());
In this case, I decided to format the first column, but it would be a very good practise to define a constant in your table model.
The best part of this is that you can reuse your code with other tables that make use of the Timestamp data type.
Hope this helps!
Upvotes: 3
Reputation: 1461
I found a solution, and here it is
@Override
public Class<? extends Object> getColumnClass(int column) {
String value = getValueAt(0, column).getClass().toString();
if (value.equalsIgnoreCase("class java.sql.Timestamp")) {
return JTextField.class;
}
return getValueAt(0, column).getClass();
}
Is there a better way to do it?
Upvotes: 1