我创造了一个简单的
JTable
按照我的习惯
DefaultTableCellRenderer
. 它本身运行良好(为最后一列着色)。但只要我选择一行或过滤/取消过滤,该行就会被着色,即使它根本不应该被着色。
我的渲染器:
public class StatusCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int col) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
table.convertRowIndexToModel(row), col);
DataTableModel model = (DataTableModel) table.getModel();
String data = model.getValueAt(table.convertRowIndexToModel(row), col).toString();
if (col == 3 && data.equalsIgnoreCase("successful") && !data.isEmpty()) {
c.setBackground(Color.GREEN);
}
if (col == 3 && !data.equalsIgnoreCase("successful") && !data.isEmpty()) {
c.setBackground(new Color(255, 51, 51));
}
return c;
}
}
它最初的样子(以及它一直应该的样子):
选择两行(顶部和底部)后:
如你所见,有几行是绿色的,根本不应该被涂上颜色。更令人不安的是,我只选择了绿色块的顶行和底行,这意味着它也会自动为中间的行上色。
我如何才能停止这种行为,只给第一张图片中显示的行上色?
接受的答案非常有助于我克服这些问题,这是最后的代码:
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int col) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
table.convertRowIndexToModel(row), table.convertColumnIndexToModel(col));
DataTableModel model = (DataTableModel) table.getModel();
String data = model.getValueAt(table.convertRowIndexToModel(row), table.convertColumnIndexToModel(col))
.toString();
if (!isSelected) {
if (col == 3 && data.equalsIgnoreCase("successful") && !data.isEmpty()) {
c.setBackground(Color.GREEN);
} else if (col == 3 && !data.equalsIgnoreCase("successful") && !data.isEmpty()) {
c.setBackground(new Color(255, 51, 51));
} else {
c.setBackground(Color.WHITE);
}
} else {
c.setBackground(c.getBackground());
}
return c;
}
如果选择了单元格,它将变为蓝色;如果没有,则根据值,它将变为白色、绿色或红色