This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
I'm trying to come up with a way to have a column in my JTable display a date but in the format of only showing time (4:00 PM or 1600). It's for a time entry on a daily basis so I don't need the user entering the date. I also don't want the user to get a jumbled date time format when they double click the cell.
Can anyone point me in the right direction for some custom TableCellRenderer and/or CellEditor example that would do something like this?
All I seem to find on the web are Date/Time formats or if it's a time format displayed, once you double click the cell it shows you the whole date/time (Mon Mar 05 11:30:26 EST 2012) which is tedious to edit since the user should be able to just enter 1600 or 4PM and have it adjust the time.
I thought about just using a string but I wasn't sure if there was some Java format that would do it for me. If I use a string then I will need to develop the method which tries to convert the user's input into a valid result (input could be 1600, 4PM 4:00PM, 4 PM). I know that for dates Java already does the checks on it's own, for instance, I can write 12/22/2011 or 12/2011/22 and Java will automatically convert it to the set format since it is a Date object.
You're right that you need both a renderer and an editor. Those examples probably only used a custom renderer.
The renderer is the easiest. Take a look at the source of JTable (found in src.zip inside the JDK folder). Look for static class DateRenderer and see how it's implemented. You basically do the same but with a different DateFormat.
The editor is slightly more difficult. The default uses static class GenericEditor which uses toString() for displaying the value initially and the constructor that takes a String for parsing the value back. You need to change both. Let's take GenericEditor as a template and modify it as needed: