将图像添加到JTable Cell

时间:2013-05-30 23:05:16

标签: java swing jtable icons defaulttablemodel

我想要动态地将数据添加到包括图像的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});

ImageRenderer类

public class ImageRender extends DefaultTableCellRenderer{

   ImageIcon icon = null;

   public ImageRender(String iconName)
   {
      icon = new ImageIcon(getClass().getResource(iconName));
   }  
}

这不起作用。只有路径名称显示在屏幕上。我该如何解决这个问题?

1 个答案:

答案 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;
    }
};