首页 > 解决方案 > 在 Java 中动态命名类实例

问题描述

我正在尝试使用 foreach 循环为列表中的所有内容创建一个按钮:

List<String> aList= new ArrayList<>();

然后使用 foreach 循环;

for(String aString: aList){
    // Some code here to dynamically name buttons with the string 'aString';
}

标签: javaloopsbuttoncontrols

解决方案


变量名必须在编译时确定,因此不能是动态对象名。

如果您希望能够给您的 Button 名称,您可以使用 Hashmap

Map<String, Button> map = new HashMap<>();
//Add objects to the map like this (e.g):

for(String aString:aList){
map.put(aString, new Button());
}

并像这样检索对象:


Button mc = map.get(name);

如果您只是想向框架添加按钮,请尝试以下代码:

    for(int i=0; i<aList.size(); i++){
            Button temp = new Button();
            temp.setName(aList.get(i));
            temp.setLabel(aList.get(i));
        //write logic to add to frame/panel
        }



或者

  for(String aString:aList){
            Button tempButton = new Button();
            tempButton.setLabel(aString);
            tempButton.setName(aString);
            //write logic to add to frame/panel

        }


推荐阅读