JTable DefaultCellRenderer doesn't work on BigDecimal Type when I set Object.class
It is weird that I set my JTable cell renderer like this:
setDefaultRenderer(Object.class, new MyTableRenderer());
My table renderer works like this:
class MyTableRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component comp = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
Font font = comp.getFont();
if (table.getModel().getValueAt(row, 0).equals(BUY)) {
comp.setFont(font.deriveFont(Font.BOLD));
comp.setForeground(BUY_COLOR);
}
else {
comp.setFont(font.deriveFont(Font.BOLD开发者_运维技巧));
comp.setForeground(SELL_COLOR);
}
return comp;
}
}
But it turns out, it didin't apply those columns that have type "BigDecimal", Other String fields are all working fine.
And then, I add one more line:
setDefaultRenderer(BigDecimal.class, new MyTableRenderer());
Then everything just work fine. Why it is like this?
JTable by default installs a renderer for type Number. BigDecimal is-a Number so the default renderer is used instead of your custom renderer.
BTW: your custom renderer is buggy in that it doesn't take potentially sorted/filtered rows into account (the row/column index params of the method are view coordinates).
@eugener: your answer is wrong - it's not the storage that's important but the lookup ;-)
Cheers Jeanette
Take look at the source code of the JTable
:
public void setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer) {
if (renderer != null) {
defaultRenderersByColumnClass.put(columnClass, renderer);
} else {
defaultRenderersByColumnClass.remove(columnClass);
}
}
It uses a map where column class is a key and means that class comparison is literal. This should explain the reason for behavior you're experiencing. This is by design.
精彩评论