在 Java 中动态命名 Class 个实例
Dynamically Naming Class Instances in Java
我正在尝试使用 foreach 循环为列表中的所有内容创建一个按钮:
List<String> aList= new ArrayList<>();
然后使用foreach循环;
for(String aString: aList){
// Some code here to dynamically name buttons with the string 'aString';
}
变量名必须在编译时确定,因此不能是动态对象名。
如果你想给你的 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
}
我正在尝试使用 foreach 循环为列表中的所有内容创建一个按钮:
List<String> aList= new ArrayList<>();
然后使用foreach循环;
for(String aString: aList){
// Some code here to dynamically name buttons with the string 'aString';
}
变量名必须在编译时确定,因此不能是动态对象名。
如果你想给你的 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
}