java - 在 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
}
推荐阅读
- php - 我的 php 表单停止工作。之前还好好的
- c++ - 我应该如何在 C++ 中使用数组作为类成员?
- regex - 如何重置 $1 perl 变量?
- python - 令牌授权失败时从连接烧瓶服务器发送自定义响应
- laravel - 使用 firstWhere 访问 Laravel Blade 中的属性
- html - href 链接不可点击(似乎在 chrome 检查中工作)
- python - 在python中移动缺少数据的行
- javascript - 数组的总和索引值
- java - 使用 List 属性测试 Bean 时出现问题
- java - 如何使用 .bat 文件中的特定 JRE 版本运行 .jar 文件?