更改JTable中行的背景颜色 [英] Change the background color of a row in a JTable

查看:529
本文介绍了更改JTable中行的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有3列的JTable。我为这3个列设置了 TableCellRenderer (可能不是很有效?)。

I have a JTable with 3 columns. I've set the TableCellRenderer for all the 3 columns like this (maybe not very effective?).

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

getTableCellRendererComponent()返回每行具有随机背景颜色的Component。

如何在程序运行时将背景更改为其他随机颜色?

The getTableCellRendererComponent() returns a Component with a random background color for each row.
How could I change the background to an other random color while the program is running?

推荐答案

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

One way would be store the current colour for each row within the model. Here's a simple model that is fixed at 3 columns and 3 rows:

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);
    }
}

请注意 setRowColour 调用 fireTableRowsUpdated ;这将导致表的那一行被更新。

Note that setRowColour calls fireTableRowsUpdated; this will cause just that row of the table to be updated.

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

The renderer can get the model from the table:

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;
    }
}

更改行的颜色非常简单:

Changing a row's colour would be as simple as:

model.setRowColour(1, Color.YELLOW);

这篇关于更改JTable中行的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆