Ed Mirfin
Ed Mirfin

Reputation: 1

How to call a variable using another variable?

So I have 44 buttons in my program, and for one of my methods I want to re-enable all of them. the buttons are easily named btn1, btn2, btn3...btn44. Is there a way I can use a for loop to enable all of them?

I would love to do something like this but I cannot find the resources necessary.

for(int i == 0, i < 44, i++){
  btn<i>.setEnabled(true);
}

Without that I would have to go through each button

btn1.setEnabled(true);
btn2.setEnabled(true);
...
btn44.setEnabled(true);

I know this alternate method isn't that bad but I have similar areas in my code where a technique like the one I am looking for would be very useful. Thank you!

Upvotes: 0

Views: 81

Answers (3)

blurfus
blurfus

Reputation: 14031

You could add you Buttons to a collection, like a List (if you have not done so already). Then it's easier to iterate over them.

    // this list will grow automatically when you add new elements
    List<Button> buttons = new ArrayList<>();

    // when you create a button in your code, add them to your collection/list
    buttons.add(new Button("1"));
    buttons.add(new Button("2"));
    buttons.add(new Button("3"));
    buttons.add(new Button("4"));
    buttons.add(new Button("5"));
    // etc.

    // in Java 8 you can use lambdas to update your buttons like this
    buttons.forEach(button -> button.setEnabled(true));

Just make sure you are importing the correct version of List.

I.e make sure you use this list import java.util.List; and not the one in the windowing toolkit (i.e. not import java.awt.List;)

Upvotes: 0

OscarRyz
OscarRyz

Reputation: 199225

Create a list to store all the buttons and the iterate it.

...
List<Button> buttons = new ArrayList<>();
buttons.add(btn1);
buttons.add(btn2);
...
buttons.add(btn42);

And then use that list for mass actions:

void setStatus(boolean enabled) {
   for (Button b : buttons ) {
      b.setEnabled(enabled);
   }
}

Upvotes: 2

hyperneutrino
hyperneutrino

Reputation: 5425

You should make an array of buttons:

Button[] buttons = new Button[44];
for (int i = 0; i < 44; i++) {
    // Do stuff with buttons[i]
}

You can't get the value of a variable using its string name representation because that would not compile very well; it is possible but not just using Java and it would require some weird roundabout way of doing it. Just use an array.

Upvotes: 3

Related Questions