Reputation: 319
I would like to have a loop that will run through each of the images i have. I would like to draw them to the screen and it works fine if i draw each image separately but it uses a lot of code. Whilst using a loop to paint each image should uuse a lot less code. This is my code.
String image[] = {"carA", "carB"};
for(int i = 0; i < image.length; i++){
g.drawImage(image[i].getImage(), image[i].getX(), image[i].getY(),
image[i].getWidth(), image[i].getHeight(), this);
}
It says the problem is that strings are being used. The getX() and getY() etc finds out the x and y coordinates. How can I get this to work?
Upvotes: 0
Views: 128
Reputation: 30875
String is a type that store characters. So it can not be used for your requirements.
To meet the requirements you should crate own type.
Good place to start i to create a interface that your class will be using.
public interface IMichaelImage {
int getX();
int getY();
Image getImage();
}
Then you need to create a class that will be able to store the information that you program logic will use
public MichaelImage implements IMichaelImage {
private int x = 0;
private int y = 0;
private Image image;
public MichaelImage(Image image) {
this.image = image;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
@Override
public int getX() {
return this.x;
]
@Override
public int getY() {
return this.x;
}
public Image getImage() {
return this.image;
}
}
On the and you will have something like this
Collection<IMichaelImage> images = loadImages();
for(IMichaelImage image : images) {
g.drawImage(image.getImage(), image.getX(), image.getY());
}
Upvotes: 0
Reputation: 106
You should initialize all data about images, try this example:
String imageDatas[][] = {
{"image_path_1.jpg", "0", "0", "100", "100"},
{"image_path_2.jpg", "100", "0", "100", "100"}
};
for (String[] imageData : imageDatas) {
String filePath = imageData[0];
int x = Integer.parseInt(imageData[1]);
int y = Integer.parseInt(imageData[2]);
int width = Integer.parseInt(imageData[3]);
int height = Integer.parseInt(imageData[4]);
Image img = Toolkit.getDefaultToolkit().getImage(filePath);
g.drawImage(img, x, y, width, height, this);
}
Upvotes: 0
Reputation: 4671
You are trying to call getImage /getX / getY on the String object. You should load your Image first into the Image object like that
Image img1 = Toolkit.getDefaultToolkit().getImage(image[i]);
Upvotes: 1