0

I have 25 jButtons and i want to change their texts from a loop. Here is my code for 1 button..

void changeText(){
            jButton1.setText(jButton1.getText().toUpperCase());

    }

I want to do the same for all other buttons without writing a method for each.

Is it possible to use something like this?

void changeText(){
        for(int i=0;i<25;i++){
            String x = "jButton"+i;
            x.setText(x.getText().toUpperCase());
        }
    }

Surely this wont work. Please suggest me a method.

Hasi007
  • 146
  • 2
  • 14
  • you could pass a JButton as an argument to changeText() and inside a loop (iterating an array or collection holding your JButton objects) call it – Dan Feb 08 '13 at 17:10

1 Answers1

2

You can do this by adding the buttons to a collection.

Something like this:

// initialization of jbuttons:
List<JButton> buttons = new ArrayList<JButton>();
JButton jbutton1 = new JButton();
// .. set properties
buttons.add(jbutton1);

// add more jbuttons to the list

Later you can iterate over the list of buttons:

for (JButton button : buttons) {
  button.setText(button.getText().toUpperCase());
}
micha
  • 47,774
  • 16
  • 73
  • 80