0

As the title says, I need to replace part of the name of the variable with the number of for loop iterations.

In my code, the variables are a grid of buttons on Swing, going from a1 to c3. I have to re-color all of the buttons dependent on the p1grid[] array. I cannot (to my knowledge) put them in an array of their own since they are buttons. Here's my code:

for (int i = 1; i < 4; i++) {
    if (p1grid[i - 1].equals("empty"))
        ("a" + i).setBackground(Color.LIGHT_GRAY);
    else
        ("a" + i).setBackground(Color.RED);
}
2
  • 5
    Put the buttons into an array or a Map. Nothing about them being Buttons stops you doing this. Commented May 7, 2019 at 16:06
  • You can put them in an array. Just remember that you have to add them individually, not the whole array together (loop on the array and add each one). Commented May 7, 2019 at 16:26

1 Answer 1

1

Your current code will not compile, because ("a"+i) is a string which does not have a setBackground() method.

Assuming the class for for buttons is Button. Thus you can do something like:

   List<Button> buttons = new ArrayList<Button>;
   buttons.add(a1);buttons.add(a2);...

Then modify the background using:

for (int i = 1; i < 4; i++) {
    if (p1grid[i - 1].equals("empty"))
        buttons.get(i-1).setBackground(Color.LIGHT_GRAY);
    else
         buttons.get(i-1)..setBackground(Color.RED);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.