user2297639
user2297639

Reputation: 81

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. 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

Answers (2)

camickr
camickr

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

Freak
Freak

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

Related Questions