-2

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

mKorbel
  • 109,525
  • 20
  • 134
  • 319
batsta13
  • 549
  • 2
  • 12
  • 26

1 Answers1

2

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;
    }
};
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366