You want the file name only to appear in the list, but you're adding the image instead. So instead of
try{
ImageIcon ii = new ImageIcon(ImageIO.read(listOfFiles[i]));
listModel.add(count++, ii);
}
catch(IOException e){}
Just do
listModel.add(count++, listOfFiles[i].getName());
If you want to store the ImageIcon and the file name into one object, you can create a wrapper class. Something like
public class NamedImageIcon {
private String imageName;
private ImageIcon icon;
public NamedImageIcon(ImagIcon icon, String imageName) {
this.icon = icon;
this.imageName = imageName;
}
// getters and setters
@Override
public String toString() {
return imageName;
}
}
No when you're looping you can create a wrapper for the name and for the image. You can then add instances of NamedImageIcon
to the DefaultListModel
. And since you override the toString(), the only thing that will appear in the list is the name. So when you select the name from the list, you will have direct access the corresponding image