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
  •  | 
  •  

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?

有帮助吗?

解决方案

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 ...
}

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top