-1

I have a JTable with numbers. I know how to change color of one cell or all cells. But how to change color of cell in and animate it ? For example, The first cell of red, there is a delay, and the second cell is painted in the same red color and so on.

I inherited class 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;
    }
}

And set method table.setDefaultRenderer(Object.class, new paintCell());

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
mr.ANDREW
  • 51
  • 1
  • 7
  • 1
    You might try establishing a Swing based `Timer` to call `repaint()` on the table every NN milliseconds and then adjust the cells color each time the renderer is called. If you cannot get it working based on that, post an [SSCCE](http://sscce.org/) of your best attempt. – Andrew Thompson May 02 '13 at 12:58

2 Answers2

1

Create the javax.swing.Timer object. Add the int pointer field in your PaintCell renderer class and increase it on Timer.actionPerfomed(). Then, in PaintCell.getTableCellRendererComponent method cast the value parameter to int type (as you said, you have a digits in cells) and compare it with your pointer field. If it equals or less, set cells' background to red.

SeniorJD
  • 6,946
  • 4
  • 36
  • 53
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 is faster than me... But I wrote the code without his answer)

johnchen902
  • 9,531
  • 1
  • 27
  • 69