Frage

My code is given below.I want to display all the image names into the jList from a folder.But the following code displays the names in the output screen not in the jList.Please help to solve this

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {     
String path = "C:\\Users\\Dell\\Documents\\NetBeansProjects\\pasword2\\src\\images\\";


 File folder = new File(path);
    File[] listOfFiles = folder.listFiles();
    DefaultListModel listModel = new DefaultListModel();
    int count = 0;
    for (int i = 0; i < listOfFiles.length; i++)
    {
        System.out.println("check path"+listOfFiles[i]);
        String name = listOfFiles[i].toString();
        // load only JPEGs
        if ( name.endsWith("jpg")||name.endsWith("bmp") ) {
            try
            {
            ImageIcon ii = new ImageIcon(ImageIO.read(listOfFiles[i]));
            listModel.add(count++, ii);
            }
            catch(IOException e){}
        }
    }
    jList1.setModel(listModel);
}
War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top