How to rename set of JButtons?

我的梦境 提交于 2019-12-13 03:58:36

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/14777727/how-to-rename-set-of-jbuttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!