java - Java 中动态命名类实例

标签 java loops button controls

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

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

然后使用 foreach 循环;

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

最佳答案

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

如果您希望能够给出按钮名称,可以使用 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

        }

关于java - Java 中动态命名类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59960320/

相关文章:

java - ReadableByteChannel.read() 的行为

java - 重用对象实例与在每次更新时创建新实例

导出项目后 Java list 文件发生更改

php - 不使用循环向数组添加值

android - 如何将文本添加到edittext

jquery - Bootstrap - 谁能给我任何例子,如何设置 JS 按钮?

java - Java如何与http网页上的按钮进行交互?

java - 使用模式在 Jasper Reports 中格式化货币

javascript - 增加一个具有动态名称的数组

返回遍历列表列表的循环内列表的名称