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?
Asked
Active
Viewed 124 times
2
-
Are you trying to create "dynamic variable names"? – Dominik Sandjaja Nov 20 '12 at 15:32
-
I don't know honestly. I'm new to Java. – setherj Nov 20 '12 at 15:34
2 Answers
2
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 ...
}

yiwei
- 4,022
- 9
- 36
- 54
-
How would an array be set up in this situation? I think I will be using an array instead of an array list. – setherj Nov 20 '12 at 17:11
-
Nvm. I see that it would be 'JToggleButton m_jTogBtn[][] = new JToggleButton[20][20];' – setherj Nov 20 '12 at 17:27
-
1Where the comment in your code says to insert JToggleButtons to the ArrayList, how do I go about that? Is there a general way or do I have to go through all 400 buttons sending them each to a specific slot in my array? – setherj Nov 20 '12 at 17:43
1
The easiest way to achieve this by putting all the buttons into an array, or an ArrayList
.

NPE
- 486,780
- 108
- 951
- 1,012