简体   繁体   中英

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);
        }
    }
}    

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(...);

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM