Home > other >  How to access value of JLabel dynamically in Java swing?
How to access value of JLabel dynamically in Java swing?

Time:12-13

I got almost around 11 Jlabels with the names of num1, num2.... num{11}. These Jlabel variable name has Prefix of name. But I want to get value from these text field something like that:

(prefix   i).setText("something")

But that gives me an error.. Is there any way to setText of these labels dynamically?

I did it though.. But the code is not DRY anymore :' (

if(i == 0) {
            num0.setText(data[i]   "");
            if(data[i] == 0) {
               num0.setText("");
            }
        } 
        if(i == 1) {
            num1.setText(data[i]   "");
            if(data[i] == 0) {
               num1.setText("");
            }
        } 
        if(i == 2) {
            num2.setText(data[i]   "");
            if(data[i] == 0) {
               num2.setText("");
            }
        } 
        if(i == 3) {
            num3.setText(data[i]   "");
            if(data[i] == 0) {
               num3.setText("");
            }
        } 
        if(i == 4) {
            num4.setText(data[i]   "");
            if(data[i] == 0) {
               num4.setText("");
            }
        } 
        if(i == 5) {
            num5.setText(data[i]   "");
            if(data[i] == 0) {
               num5.setText("");
            }
        } 
        if(i == 6) {
            num6.setText(data[i]   "");
            if(data[i] == 0) {
               num6.setText("");
            }
        } 
        if(i == 7) {
            num7.setText(data[i]   "");
            if(data[i] == 0) {
               num7.setText("");
            }
        } 
        if(i == 8) {
            num8.setText(data[i]   "");
            if(data[i] == 0) {
               num8.setText("");
            }
        } 
        if(i == 9) {
            num9.setText(data[i]   "");
            if(data[i] == 0) {
               num9.setText("");
            }
        } 
        if(i == 10) {
            num10.setText(data[i]   "");
            if(data[i] == 0) {
               num10.setText("");
            }
        } 
        if(i == 11) {
            num11.setText(data[i]   "");
            if(data[i] == 0) {
               num11.setText("");
            }
        }

CodePudding user response:

Place your JLabels into an array or ArrayList and access them by index.

ArrayList<JLabel> labels = new ArrayList<>();
labels.add(num1);
labels.add(num2);
...

int i=0;
for (JLabel label: labels) {
    label.setText(data[i]   "");
    if(data[i] == 0) {
       label.setText("");
    }
    i  ;
}

In case you just want to append something to the label, you can use

label.setText(label.getText() "-appendix");
  • Related