Java 更改 JTable 中一行的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3875607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:12:34  来源:igfitidea点击:

Change the background color of a row in a JTable

javajtabletablecellrenderer

提问by user

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

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

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

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?

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

采纳答案by Richard Fearn

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:

一种方法是存储模型中每一行的当前颜色。这是一个固定为 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);
    }
}

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

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

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

回答by Mark Peters

This is basically as simple as repainting the table. I haven't found a way to selectively repaint just one row/column/cell however.

这基本上就像重新粉刷桌子一样简单。然而,我还没有找到一种方法来选择性地重新绘制一行/列/单元格。

In this example, clicking on the button changes the background color for a row and then calls repaint.

在这个例子中,点击按钮会改变一行的背景颜色,然后调用 repaint。

public class TableTest {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Color[] rowColors = new Color[] {
                randomColor(), randomColor(), randomColor()
        };
        final JTable table = new JTable(3, 3);
        table.setDefaultRenderer(Object.class, new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus,
                    int row, int column) {
                JPanel pane = new JPanel();
                pane.setBackground(rowColors[row]);
                return pane;
            }
        });
        frame.setLayout(new BorderLayout());

        JButton btn = new JButton("Change row2's color");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                rowColors[1] = randomColor();
                table.repaint();
            }
        });

        frame.add(table, BorderLayout.NORTH);
        frame.add(btn, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

    private static Color randomColor() {
        Random rnd = new Random();
        return new Color(rnd.nextInt(256),
                rnd.nextInt(256), rnd.nextInt(256));
    }
}

回答by Andy Thomas

The call to getTableCellRendererComponent(...)includes the value of the cell for which a renderer is sought.

调用getTableCellRendererComponent(...)包括寻找渲染器的单元格的值。

You can use that value to compute a color. If you're also using an AbstractTableModel, you can provide a value of arbitrary type to your renderer.

您可以使用该值来计算颜色。如果您还使用 AbstractTableModel,则可以为渲染器提供任意类型的值。

Once you have a color, you can setBackground()on the component that you're returning.

一旦你有了颜色,你就可以setBackground()在你要返回的组件上。

回答by camickr

The other answers given here work well since you use the same renderer in every column.

此处给出的其他答案效果很好,因为您在每一列中使用相同的渲染器。

However, I tend to believe that generally when using a JTable you will have different types of data in each columm and therefore you won't be using the same renderer for each column. In these cases you may find the Table Row Renderingapproach helpfull.

但是,我倾向于相信,通常在使用 JTable 时,每个列中都会有不同类型的数据,因此您不会对每一列使用相同的渲染器。在这些情况下,您可能会发现表格行渲染方法很有帮助。

回答by Olivier Faucheux

Resumee of Richard Fearn's answer , to make each second line gray:

理查德·费恩 (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;
    }
});