更改 JTable 中行的背景色

2022-09-02 00:07:29

我有一个包含3列的JTable。我已经为所有3列设置了这样的(也许不是很有效?TableCellRenderer

 for (int i = 0; i < 3; i++) {
     myJTable.getColumnModel().getColumn(i).setCellRenderer(renderer);
 }

返回一个组件,每行都有随机背景色。
如何在程序运行时将背景更改为其他随机颜色?getTableCellRendererComponent()


答案 1

理查德·费恩(Richard Fearn)的答案的简历,使每一行都变为灰色:

jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
        return c;
    }
});

答案 2

一种方法是存储模型中每行的当前颜色。下面是一个固定在 3 列和 3 行的简单模型:

static class MyTableModel extends DefaultTableModel {

    List<Color> rowColours = Arrays.asList(
        Color.RED,
        Color.GREEN,
        Color.CYAN
    );

    public void setRowColour(int row, Color c) {
        rowColours.set(row, c);
        fireTableRowsUpdated(row, row);
    }

    public Color getRowColour(int row) {
        return rowColours.get(row);
    }

    @Override
    public int getRowCount() {
        return 3;
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public Object getValueAt(int row, int column) {
        return String.format("%d %d", row, column);
    }
}

请注意,调用 ;这将导致仅更新表的那一行。setRowColourfireTableRowsUpdated

渲染器可以从表中获取模型:

static class MyTableCellRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        MyTableModel model = (MyTableModel) table.getModel();
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(model.getRowColour(row));
        return c;
    }
}

更改行的颜色非常简单:

model.setRowColour(1, Color.YELLOW);

推荐