着色行可以执行使用改进的TableCellRenderer
在第二复选框。我已经创建了一个自定义的TableCellRenderer
,如下所示。
ColorTableRenderer.java
它可以添加行被标记为灰色,并清除所有标记的行。
public class ColorTableRenderer extends DefaultTableCellRenderer {
//contains row indexes which need to color
private final List<Integer> colorIndexes = new ArrayList<>();
//add new index to show as color
public void addColorIndex(Integer index) {
colorIndexes.add(index);
}
//clear all color indexes
public void clearColorIndexes() {
colorIndexes.clear();
}
private boolean isColorIndex(Integer index) {
return colorIndexes.contains(index);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (isColorIndex(row)) {//check if marked as colored
component.setBackground(Color.LIGHT_GRAY);//highlight color
} else {
component.setBackground(Color.WHITE);//other color
}
return component;
}
}
使用ColorTableRenderer
设置ColorTableRenderer
使用下列方法之一表。
ColorTableRenderer renderer = new ColorTableRenderer();
//set TableCellRenderer into a specified JTable column class
table.setDefaultRenderer(String[].class, renderer);
//or, set TableCellRenderer into a specified JTable column
table.getColumnModel().getColumn(columnIndex).setCellRenderer(renderer);
考虑到您的代码,您可以添加以下修改以使选定的行颜色。
renderer.clearColorIndexes();
for (int m = 0; m < tb_doublon.getRowCount(); m++) {
Statement statdouble = null;
ResultSet rsdouble = null;
//I get the value of the cell of the column 1 :id, line : i
String id = (String) tb_doublon.getValueAt(m, 1);
String cli = (String) tb_doublon.getValueAt(m, 2);
//i browse the other table to enable or gray out the lines existing in that table with th id
String doubleexistant = "select * from doublon where id='" + id + "' and cli='" + cli + "'";
statdouble = conn.createStatement();
rsdouble = statdouble.executeQuery(doubleexistant);
while (rsdouble.next()) {
renderer.addColorIndex(m);
}
}
这是我测试的屏幕截图
你必须创建一个定制的表格模型。请添加关于您的表格模型的信息。此外,我不建议在循环内运行sql语句。你可以用适当的方式管理它。 –