John Lennon
John Lennon

Reputation: 1

How to declare labels in loop?

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

Answers (2)

Reimeus
Reimeus

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

Jean Logeart
Jean Logeart

Reputation: 53809

As a side note, in Java 8:

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

Upvotes: 2

Related Questions