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