[英]How do I use a string as an argument to represent an object in Java?
Pardon my lack of knowledge and maybe improper terminology, as I'm new to Java. 请原谅我缺乏知识,也许还有不恰当的术语,因为我是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
: 此外,在另一个类,其中playerCard[]
是阵列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. 显然, setIcon
不会将String用作参数,因此将无法使用。 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. 由于这是一副纸牌,所以排名不一定总是“ C”和“ A”,但我这样做是为了简化。
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));
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 由于JLabel
图标总是获取Icon
对象,因此您可以在此处设置图标的名称,然后将其传递给setIcon。没有JLable#setIcon(String)
重载方法,只有一种方法是JLable#setIcon(Icon)
。请尝试这个
Icon icon = new ImageIcon("Cards." + suit + rank);
//here could be any resource path and name like "/foo/bar/baz.png"
playerCard[playerTurn].setIcon(icon);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.