Impmaster
Impmaster

Reputation: 187

How to find the name of an object in java

I want to do something where I go through a arrayList, and each time I go through, I go through one object, and I initialize it by calling on the file path. However, it doesn't work because I don't know how to call the file.

For example, I have an Image called image. I want to link it to a file named image in "data". I add it to the arrayList named imageList, then I call on the for loop.

I have this as code.

    for (Image image: imageList) {
        image = new Image("data/" + image.getName());
    }

getName() is a method in the library I am using, where if I set a name to the image, it has a name. However, it doesn't just call the name.

If I have three images named "background", "character", and "Bob", where each image relates to an image with the same name as the object, how can I call upon them?

Sorry if I'm a little bit confusing.

Upvotes: 0

Views: 185

Answers (1)

Reimeus
Reimeus

Reputation: 159754

Use a Map

String[] imageNames = { "background", "character", "Bob" };
Map<String, Image> map = new HashMap<String, Image>();

for (String imageName: imageNames) {
    Image backGroundImage = 
            ImageIO.read(getClass().getResource("/data/" + imageName + ".png"));
    map.put(imageName, backGroundImage);
}

Upvotes: 1

Related Questions