maduranga
maduranga

Reputation: 183

Problem regarding loops. I need to access 10 labels through a loop in java?

I have a problem regarding loops. I need to access 10 labels which have names like label1, label2, label3 .... etc. I need to know whether I can access those labels by going through a loop in java?

Upvotes: 4

Views: 561

Answers (6)

Coder
Coder

Reputation: 2044

Put your labels in to LinkList or array Then you can access those array or linkList on a loop

Upvotes: 4

user905686
user905686

Reputation: 4634

If you cannot change the labels names / put them into an array you can make an array of references to the labels and fill it at the beginning of your program with the list of your labels.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533520

If you are talking about Java labels, you can use a switch statement instead. If you are talking about objects such as a JLabel, use an array or ArrayList.

Upvotes: 0

Sebastiaan van den Broek
Sebastiaan van den Broek

Reputation: 6331

'Access to labels' is kinda vague. Are you referring to different instances of java.awt.label? If so you can simply loop over them when they're in a list with a for-each statement.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240900

How about using List or an array

List<JLabel> labels = new ArrayList<JLabel>();
labels.get(index);

Upvotes: 5

MByD
MByD

Reputation: 137322

Change those labels to be an array, and access it using an index.

For example:

JLabel[] labels = new JLabel[10];
for (int i = 0; i < labels.length; ++i) {
    labels[i] = new JLabel("Label " + i);
}
for (int i = 0; i < labels.length; ++i) {
    // access each label.
}

Upvotes: 4

Related Questions