Tonatiuh Matos
Tonatiuh Matos

Reputation: 13

Java - How do you make a jButton# index take the value of an int variable?

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!

Upvotes: 0

Views: 136

Answers (2)

TheRealMatthewJohnson
TheRealMatthewJohnson

Reputation: 26

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!

Upvotes: 1

Mureinik
Mureinik

Reputation: 311143

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

Upvotes: 0

Related Questions