问题
I want to change color of whole row in my JTable.
I defined the JTable:
JTable table = new JTable(data, columnNames);
where data, columnNames are the String tables.
The most common way to do this is to write own class:
public class StatusColumnCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
//Cells are by default rendered as a JLabel.
JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
//Get the status for the current row.
l.setBackground(Color.GREEN);
//Return the JLabel which renders the cell.
return l;
}
}
and call:
this.table.getColumnModel().getColumn(0).setCellRenderer(new StatusColumnCellRenderer());
But it is doesn't work. What am I doing wrong?
回答1:
You're setting the TableCellRenderer
correctly initially but then you're replacing it with this code:
for (int i = 0 ; i < table.getColumnCount(); i++)
table.getColumnModel().getColumn(i).setCellRenderer( centerRenderer );
Change it so that it sets the colored cell renderer at the correct index (and add braces(!)):
for (int i = 0; i < table.getColumnCount(); i++) {
TableColumn column = table.getColumnModel().getColumn(i);
if (i == COLOR_COLUMN) { // COLOR_COLUMN = 1
column.setCellRenderer(new StatusColumnCellRenderer());
} else {
column.setCellRenderer(centerRenderer);
}
}
回答2:
I want to change color of whole row in my JTable.
You are only adding the renderer to the first column so only the first column will be colored, not the entire row.
Check out Table Row Rendering if your actual requirement is to color all columns of the row.
来源:https://stackoverflow.com/questions/16882902/how-to-change-color-of-row-in-jtable