使用嵌套for循环显示GUI标签

问题描述 投票:0回答:1

我有10个名字存储在ArrayList名称中。

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");

我想使用GLabel对象在GUI窗口中显示这10个名称。目前,我有10个硬编码的GLabel对象接受每个单独的名称字符串,但我觉得这是非常重复的。

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);

...

我想使用循环结构来显示每一个。每个硬编码的GLabel之间的唯一区别是显示的名称和位置。每个标签的位置需要减少40。

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

我设置了这个嵌套的for循环,其思想是外部for循环将创建相隔40px的GLabel对象,内部for循环将使用取自GLabel名称的字符串名称填充每个ArrayList对象。

然而,虽然外部for循环工作(10个GLabel对象成功创建40px),内部似乎覆盖显示每个名称的每个标签,而不是预期的单个名称。

incorrect output in GUI window

我认为这个问题正在发生,因为内部循环应该只运行一次,而不是10次。但是,我不确定如何确保第一个循环运行10次而第二个循环只运行一次。

java user-interface for-loop nested nested-loops
1个回答
0
投票

跳过两个循环并在names数组上循环

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.