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



请原谅我缺乏知识和可能不恰当的术语,因为我是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);

最新更新