如何在循环中自动创建对象?为什么这段代码不起作用?
String strLbl[] = {"Model","Weight","Length","Age","Number of keys"};
JLabel lbl[] = new JLabel[5];
for (int i=0;i<strLbl.length;i++){
JLabel lbl[i] = new JLabel(strLbl[i]);
}
答案 0 :(得分:3)
数组元素赋值不允许使用类型声明:
JLabel lbl[i] = new JLabel(strLbl[i]);
应该是
lbl[i] = new JLabel(strLbl[i]);
答案 1 :(得分:2)
作为旁注,在Java 8中:
JLabel lbl[] = Arrays.stream(strLbl).map(s -> new JLabel(s)).toArray();