How to change color of cell in JTable and animate it?

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

Answers


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)


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.


Need Your Help

About comparing an integer and a float/double in C/C++

c++ c floating-point comparison int

I have the following piece of code (feel free to change the float with double):

iOS - How do you know if the device is playing something?

ios html5-video statusbar

I need to know when an HTML video started playing. I see that when it does this little play icon appears in the status bar.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.