Add JLabel with image to JList to show all the images

后端 未结 2 1430
南笙
南笙 2020-11-27 08:27

Here is my code. It does not show images in the frame and instead shows some text. would anybody please suggest me that what change I should make in the code so that it all

相关标签:
2条回答
  • 2020-11-27 08:43

    Note that I would not design the code this way, but I wanted to keep it as close to the original as practical, while making it work to display a list of images on a Windows based box.

    ListView

    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    
    public class ListView {
    
        public static void main(String[] args) throws IOException {
            String path = "C:/Documents and Settings/All Users/Documents/" +
                "My Pictures/Sample Pictures";
            JFrame frame=new JFrame();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    
            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") ) {
                    ImageIcon ii = new ImageIcon(ImageIO.read(listOfFiles[i]));
                    listModel.add(count++, ii);
                }
            }
            JList lsm=new JList(listModel);
            lsm.setVisibleRowCount(1);
    
            frame.add(new JScrollPane(lsm));
    
            frame.pack();
            frame.setVisible(true);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 09:06

    you can use listcellrenderer to display both image and text in jlist probably like the one below for showing label with icon in list

     public class myRenderer extends DefaultListCellRenderer
    {
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index,boolean isSelected, boolean cellHasFocus) 
        {
            //JLabel l = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if(value instanceof JLabel)
            {
                this.setText(((JLabel)value).getText());
                this.setIcon(((JLabel)value).getIcon());
            }
            return this;
        }
    }
    
    0 讨论(0)
提交回复
热议问题