Using a For Loop to work with many variables where the names differ only slightly (different numbers)

StackOverflow https://stackoverflow.com/questions/13476465

  •  30-11-2021
  •  | 
  •  

Question

I have a program where I am using several hundred JToggleButtons. Their names differ only slightly by numbers (e.g. jToggleButton1, jToggleButton2, jToggleButton3,...) Is there a way that I can use a for loop when doing the same thing to multiple buttons? For instance, if I want to programmatically change the states of several buttons, could I loop through them, changing the ending number of the name each time?

Was it helpful?

Solution

You could try to put them all in an array or ArrayList and use a foreach loop.

ArrayList<JToggleButton> toggleButtonArrayList = new ArrayList<JToggleButton>();
// ... insert your JToggleButtons to the ArrayList here...

for (JToggleButton myButton : toggleButtonArrayList) {
    myButton.changeSomething();
    // ...  do whatever you want here ...
}

OTHER TIPS

The easiest way to achieve this by putting all the buttons into an array, or an ArrayList.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top