如何使用字符串作为参数来表示Java中的对象?

时间:2013-04-19 03:43:58

标签: java string object

原谅我缺乏知识,也许是不正确的术语,因为我是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不使用String作为参数,因此这不起作用。我怎样才能让它发挥作用?因为这是一副牌套装和等级并不总是“C”和“A”,但我这样做是为了简化。

2 个答案:

答案 0 :(得分:4)

创建一个包含String和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));

答案 1 :(得分:1)

由于JLabel图标始终获取Icon对象,因此您可以在此处设置图标名称,然后将其传递给您的setIcon.There没有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);