Reputation: 81
Pardon my lack of knowledge and maybe improper terminology, as I'm new to Java. Here is a simplified version of my code so far:
import javax.swing.ImageIcon;
public class Cards {
static ImageIcon CA = new ImageIcon("classic-cards/1.png");
}
Also in another class where playerCard[]
is an array of JLabels
:
String suit = "C";
String rank = "A";
playerCard[playerTurn].setIcon("Cards." + suit + rank);
Obviously setIcon
does not use the String as an argument and therefore this will not work. How can I get this to work? Since this is a deck of cards suit and rank will not always be "C" and "A" but I did this for simplification.
Upvotes: 2
Views: 173
Reputation: 324207
Create a Map that contains the String and the Icon.
// Create the Map
HashMap<String, Icon> map = new HashMap<String, Icon>();
...
// Add data to the Map
map.put("Cards.CA", CA);
...
// Access the Map by your key
setIcon(map.get("Cards." + suit + rank));
Upvotes: 4
Reputation: 6883
As JLabel
icon always get the Icon
object so you can set the name of icon here and then pass it to your setIcon.There is no overloaded method of JLable#setIcon(String)
.It has only one method which is JLable#setIcon(Icon)
.Please Try this
Icon icon = new ImageIcon("Cards." + suit + rank);
//here could be any resource path and name like "/foo/bar/baz.png"
playerCard[playerTurn].setIcon(icon);
Upvotes: 1