我有一个带数字的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());
答案 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比我快......但我没有他的答案就写了代码)