Reputation: 1
How to automate creating objects in a loop? Why doesn't this code work?
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]);
}
Upvotes: 0
Views: 92
Reputation: 159754
The type declaration isnt allowed for an array element assignment:
JLabel lbl[i] = new JLabel(strLbl[i]);
should be
lbl[i] = new JLabel(strLbl[i]);
Upvotes: 3
Reputation: 53809
As a side note, in Java 8:
JLabel lbl[] = Arrays.stream(strLbl).map(s -> new JLabel(s)).toArray();
Upvotes: 2