Adding an image to JTable Cell [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-14 03:35:33

问题


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

Main class

        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

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


回答1:


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


来源:https://stackoverflow.com/questions/16847271/adding-an-image-to-jtable-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!