我想要动态地将数据添加到包括图像的JTable。这是我的代码:
String image = matchedSlots.get(i).getImagePath();
String title = matchedSlots.get(i).getTitle();
String director = matchedSlots.get(i).getDirector();
int rating = matchedSlots.get(i).getRating();
int runTime = matchedSlots.get(i).getRunningTime();
searchResults.getColumnModel().getColumn(i).setCellRenderer(new ImageRender(image));
DefaultTableModel tm = (DefaultTableModel) searchResults.getModel();
tm.addRow(new Object[] {image,title,director,rating,runTime});
public class ImageRender extends DefaultTableCellRenderer{
ImageIcon icon = null;
public ImageRender(String iconName)
{
icon = new ImageIcon(getClass().getResource(iconName));
}
}
这不起作用。只有路径名称显示在屏幕上。我该如何解决这个问题?
答案 0 :(得分:2)
最简单的方法是修改图片列的TableModel
返回Icon.class
类型
DefaultTableModel model = new DefaultTableModel(...) {
public Class getColumnClass(int column) {
Class clazz = String.class;
switch (column) {
case IMAGE_COLUMN:
clazz = Icon.class;
break;
}
return clazz;
}
};