This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi folks! I'm having some issues when a try to create a custom cell renderer for a table and I was hopping you guys can help me out. So, I'm trying to make a table and on the second column of the table it should be displayed a date (it's a Calendar object actually) and I want to format the way the date appears in the table and for this I need to create a custom cell renderer for that particular column.
Here is the CellRenderer class:
Here is my custom made Table Model for the table (don't know if it is important to see it for this particular problem but I'm adding it just in case)
And here is where I create the table model and set the custom cell renderer for the second and fourth column
The problem is that instead of a formatted text displaying the date in the manner I want, I see "java.util.GregorianCalendar[time=?,areFieldsSet=false,....(and a bunch of other stuff)". I know that on the getValueAt() of the table model I returned a Calendar object and is probably using the toString() method to write that stuff but I want to use that specific cell renderer of mine. What am I doing wrong?
I hope I'll find the solution to this problem. Thanks all!
At the moment I can't see what's going wrong with your current approach, but if you want all columns that display a Calendar to use the same renderer, you might find it simpler to use the setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer) method of JTable (you may need to override getColumnClass in your table model, though).
It's not "may need to", it's "need to". AbstractTableModel's getColumnClass method returns Object.class, and that will be used to lookup the renderer.
Sebastian, I recommend you do not extend JLabel for your custom TableCellRenderer, but DefaultTableCellRenderer. That extends JLabel itself, but it has some extra code to make sure it works properly in tables. Your renderer would then become something like this:
As you see I made two additional changes:
1) By using instanceof, you can use this renderer for other values as well (if needed). Only Calendars will be treated specially.
2) I do not call setText and return this, but I instead delegate to the default behaviour with a modified value. This will still return this, but with some extra formatting (like colouring).
How getColumnClass() should look like? Can you give me one example please! I'm asking because I've never used the Class<?> thing (I don't even know what it means) and I don't know what to return in that method.
Joined: Aug 20, 2008
Ok, I've used this getColumnClass() method
along with Rob's version of TableCellRenderer. The rest of the code is unchanged. The problem is that now I don't see anything in my table. The columns are not rendered.
What I'm doing wrong?