Specify column-specific TableCellRenderers for a JTable
-
29-06-2021 - |
Pregunta
I have a JTable
with multiple columns that display doubles, some of which are ratios, and others of which are dollar values. I'd like to specify a TableCellRenderer
to be used for the ratios, and another for the dollar values.
The java tutorials say "To specify that cells in a particular column should use a renderer, you use the TableColumn
method setCellRenderer
". This is helpful, but it's unclear to me at what point I ought to call this method on my TableColumn
s. Is there a standard way of doing this? Should I make a custom JTable
that does this in its constructor? Or a custom TableColumnModel
? Ideally I'd like to be able to do this from the custom TableModel
that I already have, though it seems unlikely that this possible.
Any help would be appreciated. Thanks
Solución
You can set a renderer on a column this way:
table.getColumnModel().getColumn(0).setCellRenderer(new TableRendererExample());
Than you can write your own renderer implementation:
class TableRendererExample extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (column == 1) {
c.setForeground(Color.gray);
}
return c;
}
}