【问题标题】:Adding an image to JTable Cell [duplicate]将图像添加到 JTable Cell [重复]
【发布时间】:2013-05-30 23:05:15
【问题描述】:

我想动态地将数据添加到 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));
   }  
}

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

【问题讨论】:

标签: java swing jtable icons defaulttablemodel


【解决方案1】:

最简单的方法是修改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;
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 2012-12-30
    • 2013-05-27
    • 2020-04-30
    • 2015-11-22
    • 2020-06-08
    相关资源
    最近更新 更多