0

I did not find any solution to my problem, so here it is.

I would like to access my JLabels. All of my labels have numbers behind them, and I would like to change these numbers and access my labels that way.

Example:

JLabel1.setText("how");
JLabel2.setText("can");
JLabel3.setText("I");
JLabel4.setText("access");
JLabel5.setText("these");
JLabel6.setText("better");

I would like to access them in a loop by changing the number at the end of the variable name, and assign values to them that way, as I will be using a lot of labels, and I would like to change the content of the labels many times.

Something like this with the above example:

String[] texts = {"how", "can", "I", "access", "these", "better"};

// this is the part I do not know, if it can be done or not.

for (int i = 0; i < texts.length; i++) {
    JLabel+(i+1).setText(texts[i]);
}

This code does not work, but I am here to seek help and find a solution for this problem. Any solution you might have, I would love to hear it, and hopefully I will understand it. I am only a Student, but I'll try my best.

I am using Netbeans IDE 8.1, and using it in GUI builder(This might not matter, but just in case).

I Huse
  • 1
  • 1
  • Java doesn't allow for dynamic variable naming. The proper tool to use here is an array or ArrayList. – Hovercraft Full Of Eels Apr 15 '17 at 20:12
  • @Hovercraft Full Of Eels How could this be done in an array, may I ask? Or perhaps, what array type should I use? – I Huse Apr 15 '17 at 20:26
  • An array of JLabel or an `ArrayList` if you go that route. You should start with any basic array tutorial and read it. Then check out ArrayList tutorials. – Hovercraft Full Of Eels Apr 15 '17 at 20:28
  • @Hovercraft Full Of Eels My love for you is going to chase you till the universe collapses. I read about the JLabel Arrays, tried to understand it, messed around with it in NetBeans, and it now works. Thank you for your time, and helpful comments. You have a great night. – I Huse Apr 15 '17 at 20:57

0 Answers0