简体   繁体   English

如何在JTable中更改单元格的颜色并对其进行动画处理?

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

I have a JTable with numbers. 我有一个带有数字的JTable。 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 我继承了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()); 并设置方法table.setDefaultRenderer(Object.class,new paintCell());

Create the javax.swing.Timer object. 创建javax.swing.Timer对象。 Add the int pointer field in your PaintCell renderer class and increase it on Timer.actionPerfomed() . PaintCell渲染器类中添加int pointer字段,并在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. 然后,在PaintCell.getTableCellRendererComponent方法中,将value参数转换为int类型(如您所说,单元格中有一个数字),并将其与pointer字段进行比较。 If it equals or less , set cells' background to red . 如果equals or less ,请将单元格的background设置为red

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) (SeniorJD比我快。。。但是我写的代码没有他的回答)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM