Search code examples
javauser-interfacefor-loopnestednested-loops

Using nested for loop to display GUI labels


I have 10 names stored in an ArrayList names.

ArrayList<String> names = new ArrayList<String>(10);

name.add(name);            // the value of this is "Zac"
names.add("undefined1");
names.add("undefined2");
names.add("undefined3");
names.add("undefined4");
names.add("undefined5");
names.add("undefined6");
names.add("undefined7");
names.add("undefined8");
names.add("undefined9");

I want to display these 10 names in a GUI window using a GLabel object. Currently, I have 10 hardcoded GLabel objects that accept each individual name string, but I feel this is very repetitive.

GLabel showName1 = new GLabel(name, (getWidth() / 2.0) - 100, (getHeight() / 2.0) - 160); // this last integer (160) is the position
showName1.move(-showName1.getWidth() / 2, -showName1.getHeight());
showName1.setColor(Color.WHITE);
add(showName1);

GLabel showName2 = new GLabel("undefined", (getWidth() / 2.0) - 100, (getHeight() / 2.0) - 120); // this last integer (120) is the position 
showName2.move(-showName2.getWidth() / 2, -showName2.getHeight());
showName2.setColor(Color.WHITE);
add(showName2);

...

I would like to use a looping construct to display each one. The only difference between each hardcoded GLabel is the name being displayed and the position. The position needs to be decremented by 40 for each label.

int counter = 10;
for (int position = 160; counter > 0; position -= 40) {
    for (String name: names) {
        GLabel showName = new GLabel(name, (getWidth() / 2.0) - 100, (getHeight() / 2.0) - position);
        showName.move(-showName.getWidth() / 2, -showName.getHeight());
        showName.setColor(Color.WHITE);
        add(showName);
    }
    counter--;
}

I set up this nested for loop with the idea that the outer for loop will create the GLabel objects 40px apart and the inner for loop will populate each GLabel object with a string name taken from the ArrayList names.

However, though the outer for loop works (10 GLabel objects are created 40px apart successfully) the inner one seems to overwrite each label displaying every name rather than a single name as intended.

incorrect output in GUI window

I think this problem is occuring because the inner loop should only run once, not 10 times. However, I'm unsure how to then ensure the first loop is run 10 times and the second is only run once.


Solution

  • Skip both loops and loop over the names array

    int position = 160;
    for (String label : names) {
        GLabel showName = new GLabel(label, (getWidth() / 2.0) - 100, (getHeight() / 2.0) - position);
        showName.move(-showName.getWidth() / 2, -showName.getHeight());
        showName.setColor(Color.WHITE);
        add(showName);
        position -= 40;
    }