Java - Changing JTable renderer per class
-
16-09-2020 - |
Question
I was hoping someone could explain something to me as I found my solution, but I don't understand why it works. I wanted to set a default renderer by Class type to a whole table, not knowing at creation where objects will be in it.
I had declared a JTable and set the default renderer to that of my own, for the Calendar
class so that any Calendar
s would give a meaningful representation, not just a toString()
of themselves.
JTable table = new JTable();
table.setDefaultRenderer(Calendar.class, new MyRenderer());
public class MyRenderer extends DefaultTableCellRenderer{
public MyRenderer() { super(); }
@Override
public void setValue(Object value){
setText(makeCalendarToDate((GregorianCalendar)value));
}
}
This would not work until I overrode the method getColumnClass
as was done Here
According to sun's Documentation, it looks like getColumnClass
should do exactly what was overridden in the example I gave above - why does it work when I override that method but not when I leave the stock implementation?
Now I can fill column's with Calendar
s pending they fill the 0th row, which is what I wanted, but what prevented me from doing that in the first place?
Solution
JTable gets the column class from the model. The answer lies in the implementation of AbstractTableModel, assuming that's what you've based your table model on. In AbstractTableModel getColumnClass has been implemented like this: return Object.class;
So, unless you override it, the column objects will always be handled as Object. This is not something the model will handle automatically. You just have to override getColumnClass, there's no way around that.