请原谅我缺乏知识和可能不恰当的术语,因为我是Java新手。下面是到目前为止我的代码的简化版本:
import javax.swing.ImageIcon;
public class Cards {
static ImageIcon CA = new ImageIcon("classic-cards/1.png");
}
在另一个类中,playerCard[]
是JLabels
的数组:
String suit = "C";
String rank = "A";
playerCard[playerTurn].setIcon("Cards." + suit + rank);
显然setIcon
不使用字符串作为参数,因此这将不起作用。我怎样才能让它工作?由于这是一副牌,花色和秩并不总是C和a,但我这样做是为了简化。
创建一个包含字符串和图标的Map。
// 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));
由于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);