我正在尝试将 gif 图像(动画)放入 JTable 单元格,但它没有被显示。正如我所读到的,JTable 组件是静态的,需要重写渲染。
关键是我有一个线程计算一些数据并将其粘贴到表格单元格中,在计算时我想显示一些旋转轮。此外,我从另一个单独的线程向表中添加行。因此,一个线程添加包含一些数据的行,另一个线程计算行中单元格的数据。
是否可以将动画图标添加到每个添加行的同一单元格中?有谁知道怎么做?
更新:现在我可以创建一个带有动画 gif 的行,但不能将这些行从线程添加到表中
public class AnimatedIconTableExample extends JFrame {
private static final long serialVersionUID = -1038271613549995183L;
public AnimatedIconTableExample() {
super("AnimatedIconTable Example");
final Object[][] data = new Object[][] {
{ "", "", new ImageIcon("src/loading.gif"),
"text" } };
final Object[] column = new Object[] { "First", "Second", "Third", "Fourth" };
DefaultTableModel model = new DefaultTableModel() {
private static final long serialVersionUID = 31150076182704312L;
public int getColumnCount() {
return column.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return (String) column[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public Class<?> getColumnClass(int col) {
return ImageIcon.class;
}
};
JTable table = new JTable(model);
setImageObserver(table);
JScrollPane pane = new JScrollPane(table);
getContentPane().add(pane);
for (int i = 0; i < 5; i++) {
new TableUpdater(model, data).start();
}
}
private void setImageObserver(JTable table) {
TableModel model = table.getModel();
int colCount = model.getColumnCount();
int rowCount = model.getRowCount();
for (int col = 0; col < colCount; col++) {
if (ImageIcon.class == model.getColumnClass(col)) {
for (int row = 0; row < rowCount; row++) {
Object obj = model.getValueAt(row, col);
ImageIcon icon = null;
if (obj instanceof ImageIcon)
icon = (ImageIcon) model.getValueAt(row, col);
if (icon != null) {
icon.setImageObserver(new CellImageObserver(table, row,
col));
}
}
}
}
}
class CellImageObserver implements ImageObserver {
JTable table;
int row;
int col;
CellImageObserver(JTable table, int row, int col) {
this.table = table;
this.row = row;
this.col = col;
}
public boolean imageUpdate(Image img, int flags, int x, int y, int w,
int h) {
if ((flags & (FRAMEBITS | ALLBITS)) != 0) {
Rectangle rect = table.getCellRect(row, col, false);
table.repaint(rect);
}
return (flags & (ALLBITS | ABORT)) == 0;
}
}
public static void main(String[] args) {
AnimatedIconTableExample frame = new AnimatedIconTableExample();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setSize(300, 150);
frame.setVisible(true);
}
}
public class TableUpdater extends Thread {
private DefaultTableModel model;
private Object[][] data;
public TableUpdater(DefaultTableModel model, Object[][] data) {
this.model = model;
this.data = data;
}
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
model.addRow(data);
}
}