Reputation: 71
I am trying to make a card game and Am running into an issue with my getImage() function. I have an String Array of the Cards ex:
private static String[] hearts = {"ah.gif","2h.gif","3h.gif","4h.gif","5h.gif","6h.gif","7h.gif","8h.gif","9h.gif","th.gif","jh.gif","qh.gif","kh.gif"};
My getImage() looks like this:
public String getImage(Card card){
if (0 == suit){
img = hearts[rank];
}
else if (1 == suit){
img = spades[rank];
}
else if (2 == suit){
img = diamond[rank];
}
else if (3 == suit){
img = clubs[rank];
}
However, because it is stored as a string, I get an error when I try to use the img as an ImgIcon Ex:
ImageIcon image = (card.getImage(card));
JLabel label = new JLabel(image);
Any Ideas? Thanks
Upvotes: 1
Views: 174
Reputation: 285405
Create an array of ImageIcons and use the String array and a for loop to create the Icon array. Simple. :)
// in declaration section
private ImageIcon heartsIcons = new ImageIcon[hearts.length];
// in code section
try {
for (int i = 0; i < hearts.length; i++) {
// you may need different code to get the Image file vs. resource.
BufferedImage img = ImageIO.read(getClass().getResource(hearts[i]));
heartsIcons[i] = new ImageIcon(img);
}
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 1