Search code examples
javaswingjlabel

Change JLabel text with a for-loop


I need help to change Jlabel texts that is a loop, I need to try something type:

String[] inputs = {"nickname0", "nickname1", "nickname2", "nickname3", "nickname4", "nickname5", "nickname6", "nickname7", "nickname8", "nickname9"};
            for(int i = 0; i<9; i++) {
                inputs[i].setText("exemple" + i);
            }

or like this:

for(int i = 0; i<9; i++) {
            (inputs + i).setText("exemple" + i);
        }

but this methods dont work, anyone have solution?


Solution

  • You actually update the content of the String objects in the array not the JLabel objects used by your application.
    So instead, add the JLabel objects in the array and iterate on them :

    JLabel lbl1 = new JLabel("nickname0");
    JLabel lbl2 = new JLabel("nickname1");
    ...
    
    JLabel[] inputs = {lbl1, lbl2, ...};
    for(int i = 0; i < inputs.length; i++) {
        inputs[i].setText("exemple" + i);
    }