Adding an image to JTable Cell [duplicate]

2019-09-25 02:40发布

问题:

This question already has an answer here:

  • Dynamically add images to JTable cells 2 answers

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