I’ve noticed a neat feature in Path Finder where it changes the date format
used to display time stamps in the main table based on the width of the
column. In RvSnoop I was allowing the user to set
a preferred format as a configuration option, but this seems much
better. It turns out that this is pretty easy to achieve in Java, just
use the following class:
publicclassDateCellRendererextendsDefaultTableCellRenderer{// Or load these from a user preference...privatestaticfinalDateFormat[]dateFormats={newSimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"),newSimpleDateFormat("yy-MM-dd HH:mm:ss.SSS"),newSimpleDateFormat("MM/dd HH:mm:ss.SSS"),newSimpleDateFormat("HH:mm:ss.SSS"),newSimpleDateFormat("HH:mm:ss.SS"),newSimpleDateFormat("HH:mm:ss.S"),newSimpleDateFormat("HH:mm:ss"),newSimpleDateFormat("HH:mm")};privateintcurrentWidth;privateFontcurrentFont;privateDateFormatcurrentFormat;privatefinalDatedate=newDate();publicComponentgetTableCellRendererComponent(JTabletable,Objectvalue,booleanisSelected,booleanhasFocus,introw,intcol){DateFormatformat=getFormat(table.getColumnModel().getColumn(col).getWidth(),table);Stringdisplayed=value!=null?format.format((Date)value):"";returnsuper.getTableCellRendererComponent(table,displayed,isSelected,hasFocus,row,col);}privateDateFormatgetFormat(intwidth,JTabletable){Fontfont=table.getFont();if(currentWidth==width&¤tFormat!=null&&font.equals(currentFont)){returncurrentFormat;}currentWidth=width;currentFont=font;FontMetricsmetrics=table.getFontMetrics(font);date.setTime(System.currentTimeMillis())for(DateFormatdf:dateFormats){if(metrics.stringWidth(df.format(date))<width){currentFormat=df;returndf;}}}currentFormat=dateFormats[dateFormats.length-1];returncurrentFormat;}}
You will need to register it with your JTable via myTable.getColumnModel().getColumn(0).setCellRenderer(myRenderer);
and away you go. You can have more or less format options by altering
the static array in the class.