如何在循环中声明标签?

时间:2014-10-13 16:06:47

标签: java for-loop label

如何在循环中自动创建对象?为什么这段代码不起作用?

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]);
}

2 个答案:

答案 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();