这是使用DefaultTableCellRenderer 的示例代码。
示例代码:
Object[] columnNames = { "A", "B", "C" };
Object[][] data = { { "abc", new Double(850.503), 53 }, { "lmn", new Double(36.23254), 6 },
{ "pqr", new Double(8.3), 7 }, { "xyz", new Double(246.0943), 23 } };
JTable table = new JTable(data, columnNames);
MyCustomTableCellRenderer cellRenderer = new MyCustomTableCellRenderer();
for (int i = 0; i < table.getColumnCount(); i++) {
table.getColumnModel().getColumn(i).setCellRenderer(cellRenderer);
}
CustomTableCellRenderer:
class MyCustomTableCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected,
boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row,
column);
if (isSelected) {
cell.setBackground(Color.green);
} else {
if (row % 2 == 0) {
cell.setBackground(Color.cyan);
} else {
cell.setBackground(Color.lightGray);
}
}
return cell;
}
}