我想改变JTable中整行的颜色。
我定义了JTable:
JTable table = new JTable(data, columnNames);
其中data,columnNames是String表。
最常见的方法是编写自己的类:
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;
}
}
并致电:
this.table.getColumnModel().getColumn(0).setCellRenderer(new StatusColumnCellRenderer());
但它不起作用。我做错了什么?
答案 0 :(得分:2)
您最初正确设置TableCellRenderer
,但之后您将使用此代码替换它:
for (int i = 0 ; i < table.getColumnCount(); i++)
table.getColumnModel().getColumn(i).setCellRenderer( centerRenderer );
更改它以便将彩色单元格渲染器设置为正确的索引(并添加大括号(!)):
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);
}
}
答案 1 :(得分:2)