如何在JTable中更改单元格的颜色并为其设置动画?

时间:2013-05-02 12:36:31

标签: java swing jtable tablecellrenderer

我有一个带数字的JTable。我知道如何改变一个细胞或所有细胞的颜色。但是如何改变细胞的颜色并使其生动? 例如,红色的第一个单元格有延迟,第二个单元格用相同的红色绘制,依此类推。

我继承了类DefaultTableCellRenderer

    class paintCell extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row,
            int column) {
        Component c = super.getTableCellRendererComponent(table, value,
                isSelected, hasFocus, row, column);
        return c;
    }
}

并设置方法 table.setDefaultRenderer(Object.class,new paintCell());

2 个答案:

答案 0 :(得分:1)

创建javax.swing.Timer对象。在int pointer渲染器类中添加PaintCell字段,然后在Timer.actionPerfomed()上增加该字段。然后,在PaintCell.getTableCellRendererComponent方法中,将value参数转换为int类型(正如您所说,您在单元格中有一个数字)并将其与您的pointer字段进行比较。如果是equals or less,请将单元格“background设置为red

答案 1 :(得分:1)

private JTable table;
private int index;
private void startAnimation() {
    Timer timer = new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            index++;
            if (index > table.getRowCount() * table.getColumnCount())
                index = 0;
            table.repaint();
        }
    });
    timer.setRepeats(true);
    timer.start();
}
class PaintCell extends DefaultTableCellRenderer {
    private static final long serialVersionUID = 1L;
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row,
            int column) {
        Component c = super.getTableCellRendererComponent(table, value,
                isSelected, hasFocus, row, column);
        int id = row * table.getRowCount() + column;
        c.setBackground(id < index ? Color.RED : null);
        return c;
    }
}

(SeniorJD比我快......但我没有他的答案就写了代码)