0

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));
Scorpiorian83
  • 469
  • 1
  • 4
  • 17
  • 3
    As `Vector` is a [legacy](http://stackoverflow.com/q/24815413/230513), also consider another [`Collection`](http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html). – trashgod Jul 20 '14 at 22:42

2 Answers2

4

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

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
2

You need to get the element from the Vector that you want to load. For example...

ImageIcon imageGraphic = new ImageIcon(imageDetails.get(0));

As has already been stated, ImageIO.read would be a better choice than simply using ImageIcon(String) as ImageIO will throw an Exception should something go wrong with reading the image.

At about this point, I might also consider using a Map instead of a Vector, this will allow you to associate the String value with the actual image. Take a look at the Collections API for more details.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366