class MyDateTabelCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
// TODO Auto-generated method stub
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Date date = (Date)value;
setText(date.getYear()+"/"+date.getMonth()+"/"+date.getDate()+" "+date.getHours()+":"+date.getMinutes());
return this;
}
}
然后用:
table.setDefaultRenderer(Date.class,new MyDateTabelCellRenderer());
这种方法只要显示的是文本都可以用这种方法,比如要将一个Long类型的变量显示成文件大小,即多少多少KB or MB,可以这样:
class MySizeTabelCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
// TODO Auto-generated method stub
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
long v = (Long)value;//当然了,要确保这一列都是Long类型的数据
String str = null;
if(v/1024 <= 0) str = v + " B";
else if(v/1024/1024 <= 0 ) str = v/1024 + " KB";
else if(v/1024/1024/1024 <= 0 ) str = v/1024/1024 + " MB";
else str = v/1024/1024/1024 + " GB";
setText(str);
return this;
}
}
然后在
table.getColumn("size").setCellRenderer(new MySizeTabelCellRenderer());
当然,也可以先转换成String在输入table。但以上方法的好处是可以自动排序,排序是仍然一原来的数据类型排序。如size仍然以Long类型从大到小排序,如果转换成String 类型的排序就乱了.
table.setAutoCreateRowSorter(true);
加上这句点击表头就能自动排序了
另外, DefaultTableCellRenderer会自动把相邻的行之间显示的颜色是不同的,且选中状态时也会自动高亮显示,若直接实现 TableCellRenderer要做出这种效果就要自己写代码了