Search code examples
javaswingjlabelimageicon

How to retrieve ImageIcon elements from Vector Strings?


I am doing this small application for image viewing. The user enters the filename for eg. image1.gif and it will populate a Vector of String and from there, I am hoping to associate it with ImageIcon to display it on a JLabel. I'm stuck currently as I'm totally lost now as in how to continue from there. Can you guys give me some advise or suggestion? Thanks!

Vector <String> imageDetails = new Vector <String>;

ImageIcon imageGraphic = new ImageIcon(imageDetails.toString());

imageLabel.setText(imageDetails.get(0));

Solution

  • You can get the Image from it's file name using ImageIO library.

    Image image = ImageIO.read(new File("images/fileName.png"));
    ImageIcon imageGraphic = new ImageIcon(image);
    

    Call JLabel#setIcon() to set the icon of the label.

    You can try any one based on image location.

    // Read from same package 
    ImageIO.read(getClass().getResourceAsStream("c.png"));
    
    // Read from images folder parallel to src in your project
    ImageIO.read(new File("images/c.jpg"));
    
    // Read from src/images folder
    ImageIO.read(getClass().getResource("/images/c.png"))
    
    // Read from src/images folder
    ImageIO.read(getClass().getResourceAsStream("/images/c.png"))
    

    Read more...

    It's worth reading Java Tutorial on Loading Images Using getResource