Lakshya Goyal
Lakshya Goyal

Reputation: 360

How to set properties of JLabel in a for loop?

I have 10 JLabels which are named label1, label2, label3, ... , label10. I want to set the text in the labels using a for loop. So what I want to be able to do is like the following:

Obviously this doesn't work.

for(int i=1; i<=10; i++){
    label+i.setText("label"+i);
}

Is there any way to actually be able to do this? I really need to do this so that I don't have to hard code everything.

Upvotes: 0

Views: 2600

Answers (2)

GKFX
GKFX

Reputation: 1400

You need to store your JLabels in an array. That is:

JLabel[] labels = new JLabel[10];
// Fill that array with your JLables
for (JLabel l : labels) {
  l.setText("label"+i);
}

And get rid of those label1, label2, label3, ... , label10 variables; they're not useful.

This type of loop is a for-each loop; for (JLabel l : labels) says "for each JLabel, l, of the array labels"; documentation here. (Thanks Frakcool!)

Upvotes: 4

Piotr Praszmo
Piotr Praszmo

Reputation: 18320

There is no way to refer to a variable without knowing its exact name at compile time. The only option is using an array (or some other collection):

JLabel label0 = new JLabel();
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JLabel label3 = new JLabel();
JLabel label4 = new JLabel();
JLabel label5 = new JLabel();
JLabel label6 = new JLabel();
JLabel label7 = new JLabel();
JLabel label8 = new JLabel();
JLabel label9 = new JLabel();

JLabel[] label = new JLabel[] { label0, label1, label2, label3, label4, label5, label6, label7, label8, label9 };
for (int i = 0; i < 10; i++) {
    label[i].setText("label" + i);
}

To avoid typing so much (and possible typos), you might create labels in loop as well:

JLabel[] label = new JLabel[10];
for (int i = 0; i < 10; i++) {
    label[i] = new JLabel();
    label[i].setText("label" + i);
}

You can still refer to particular label using label[4] syntax. Notice the array is indexed from 0 so label[0] is the first element and label[9] is the 10th (last) element.

Upvotes: 4

Related Questions