4

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?

4
  • 1
    this sounds horrible. You should restructure that code Commented Aug 23, 2011 at 10:02
  • 1
    More detail? What are labels? Why not put them into an array? Commented Aug 23, 2011 at 10:02
  • Do you mean these? download.oracle.com/javase/6/docs/api/java/awt/Label.html Commented Aug 23, 2011 at 10:03
  • Please clarify your question, the answers are using JLabel objects, but your question sounds like if you where asking about "goto labels" inside a for loop! Commented Aug 23, 2011 at 13:27

6 Answers 6

5

How about using List or an array

List<JLabel> labels = new ArrayList<JLabel>(); labels.get(index); 
Sign up to request clarification or add additional context in comments.

Comments

4

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. } 

Comments

4

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

Comments

2

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.

Comments

0

'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.

Comments

0

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.

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.