ZenenT
ZenenT

Reputation: 45

Calling/using a variable from a string value in Java?

So I have a series of jButtons named card1 to card20. I want to change the icon based on whether or not a specific condition has been fulfilled, so I'd like to make a loop and refer to each one as ("card" + i) or something similar instead of writing separate if statements for each button. The code I'm using has been added below, but is there a way to loop this if statement so each loop of the code affects a different card?

private void cardreset() {
    if (cardmatch[1] == 0) {
        card1.setIcon(back);
    }
}

This is what I'd like to do, but adding all of the "card" variables to an array beforehand creates an illegal forward reference error.

private void cardreset() {
    for(int i=1; i<=20; i++){
        if (cardmatch[i] == 0) {
            card[i].setIcon(back);
        }
    }
}    

Upvotes: 0

Views: 79

Answers (2)

mellamokb
mellamokb

Reputation: 56769

You can put them in an array and modify them that way.

JButton cards[] = { card1, card2, ..., card20 };

Then when you want to modify all the icons:

if (condition) {

  for (JButton card : cards)
    card.setIcon(...);

}

Or modify specific icons (say every other one):

for (int i = 0; i < cards.length; i++)
  if (i % 2 == 0)
    cards[i].setIcon(...);

Upvotes: 2

amit
amit

Reputation: 178411

Theoretically you could do it with reflection - but that's a really bad practice.

Instead, you should use a Map<String, Type>, and use your map to refer them.

Just for the fun of it, here how to do it with reflection, but again, I strongly advise against it.

for (int i = 0; i < 4; i ++) { 
    Field f = MyClass.class.getDeclaredField("card" + i);
    System.out.println(f.get(myClass));
}

Upvotes: 1

Related Questions