将图像添加到JTable Cell [英] Adding an image to JTable Cell

查看:133
本文介绍了将图像添加到JTable Cell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要动态地将数据添加到包括图像的JTable。这是我的代码:

I am wanting to dynamically add data to a JTable including an image. Here is my code:

        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 Class



ImageRenderer Class

public class ImageRender extends DefaultTableCellRenderer{

   ImageIcon icon = null;

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

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

This does not work. Only the path name is displayed to the screen. How can I fix this

推荐答案

最简单的方法是修改 TableModel 返回 Icon.class 图像列的类型

The simplest way is to modify the TableModel to return Icon.class type for the image column

DefaultTableModel model = new DefaultTableModel(...) { 
    public Class getColumnClass(int column) {
        Class clazz = String.class;
        switch (column) {
            case IMAGE_COLUMN:
                clazz = Icon.class;
                break;
        }
        return clazz;
    }
};

这篇关于将图像添加到JTable Cell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆