0

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

2 Answers 2

3

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]); 
Sign up to request clarification or add additional context in comments.

Comments

2

As a side note, in Java 8:

JLabel lbl[] = Arrays.stream(strLbl).map(s -> new JLabel(s)).toArray(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.