UserUser
UserUser

Reputation: 103

How do I modify 100 objects without having to write 100 lines of code? (Java)

I have a lot of JButton objects which have the names a, b, c, d, ...

I want to set all of their states according to a boolean array I have. For example, if the boolean array is [true, false, true], I want to set a's state to true, b's state to false, and c's state to true. (using JButton.setEnabled(boolean))

The problem is that I have too many objects and if I have to change their states one by one, the code is going to get long and redundant.

How do I do this in a simple way?

I'm programming in Netbeans, Java with Ant, JFrame Form.

Edit) Netbeans won't let you change the code that creates the objects. So "private javax.swing.JButton a" this part is unchangeable.

Upvotes: 0

Views: 102

Answers (1)

Jared Cohen
Jared Cohen

Reputation: 403

Having that many individual JButtons seems like something you should try to avoid at all costs, especially if you have scenarios when you need to address them all, but if you are stuck with that you could do this:

JButton a = new JButton();
JButton b = new JButton();
//Etc for all the buttons you make
        
JButton[] list = {a,b}; //Manually insert the JButtons into an array
        
for(int i=0; i < list.length; i++) //For loop through all of the buttons in the list
{
        list[i].addNotify(); //Then just use list[i] and that will be whatever JButton is at index i in the list (so in my example, i=0 is button a, i=1 is button b)
}

In the code above you insert all of your buttons into an array and then do the same function like I showed, where I called the .addNotify() function on every button in the list.

If you do have the opportunity to start from scratch and this would make things easier, I suggest putting all of the buttons into an array to begin with, such as the code below:

JButton[] list = new JButton[10]; //Manually insert the JButtons into an array
        
for(int i=0; i < list.length; i++) //For loop through all of the buttons in the list
{
        list[i] = new JButton();
        list[i].addNotify(); //Then just use list[i] and that will be whatever JButton is at index i in the list (so in my example, i=0 is button a, i=1 is button b)
}

Arrays are especially useful for these scenarios where you have a lot of objects of the same type and have the same operations done to them, so based on your description it might be a good application

Upvotes: 1

Related Questions