Shading Rows and Columns in a JTable Component
The simplest way of shading alternate rows or columns in a JTable
component is to override the prepareRenderer() method. The table
calls this method for every cell, just prior to displaying it. The
override should call the superclass and retrieve the prepared
component. It can then modify the background and foreground colors to
achieve any desired pattern of shaded rows and columns.
// This table shades every other row yellow
JTable table = new JTable() {
public Component prepareRenderer(TableCellRenderer renderer,
int rowIndex, int vColIndex) {
Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
if (rowIndex % 2 == 0 && !isCellSelected(rowIndex, vColIndex)) {
c.setBackground(Color.yellow);
} else {
// If not shaded, match the table's background
c.setBackground(getBackground());
}
return c;
}
};
// This table shades every other column yellow
table = new JTable() {
public Component prepareRenderer(TableCellRenderer renderer,
int rowIndex, int vColIndex) {
Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
if (vColIndex % 2 == 0 && !isCellSelected(rowIndex, vColIndex)) {
c.setBackground(Color.yellow);
} else {
// If not shaded, match the table's background
c.setBackground(getBackground());
}
return c;
}
};
Post a comment