0

I need to perform actions on hundreds of buttons. I'm looking for a way to use a loop for the jButton index, instead of writing hundreds of lines of code just to change the color of multiple buttons. I want something like this:

for(int i = 1; i < 100; i++){
    jButton("i").setForeground(Color.red)
}

So for example for n=18, the command executed is:

jButton18.setForeground(Color.red)...

Which obviously does not work, but there has to be a simpler way than to write a line for each button!

2 Answers2

1

If you're trying to instantiate hundreds of buttons what you'll want is to have them in an array. That would probably look something like this: JButton[] array = new JButton[100].

You can then loop through the array using your for loop and change the colour of each button like this: array[i].setForground(Color.red)).

You can initialize the buttons in a similar way by setting the values of each index like this: array[i] = JButton("textHere").

If you want to number them all differently there's a post here on how to convert numbers to strings so you can do it inside your loop.

Cheers!

Community
  • 1
  • 1
0

Put all your JButton instances in a List once you create them, and then you can just iterate over them:

for (JButton jButton : myJButtons) {
    jButton.setForeground(Color.red))
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350