Swing 如何迭代字符串,根据字符创建JLabel网格

Swing 如何迭代字符串,根据字符创建JLabel网格,swing,multidimensional-array,icons,iteration,jlabel,Swing,Multidimensional Array,Icons,Iteration,Jlabel,大家好,我想迭代字符串参数,并为字符串中的每个字符创建一个带有图标的标签,该图标与字符串中的特定字符相匹配。我希望标签位于5x5网格中 我知道这段代码只会使网格充满第一个字符,但我不确定应该在哪里进行迭代 public void makeGrid(String text){ JLabel[][] labels = new JLabel[5][5]; ImageIcon picToUse = null; for (int x = 0; x < text.length

大家好,我想迭代字符串参数,并为字符串中的每个字符创建一个带有图标的标签,该图标与字符串中的特定字符相匹配。我希望标签位于5x5网格中

我知道这段代码只会使网格充满第一个字符,但我不确定应该在哪里进行迭代

public void makeGrid(String text){
    JLabel[][] labels = new JLabel[5][5];
    ImageIcon picToUse = null;

    for (int x = 0; x < text.length(); x++){
        char c = text.charAt(x);
        if (c == 'X') {// can't see
            picToUse = OuterWall;
        } else if (c == '#') {// wall
            picToUse = Wall;
        } else if (c == '.') {// floor
            picToUse = Floor;
        } else if (c == 'G') {// gold
            picToUse = Gold;
        } else if (c == 'E') {// exit
            picToUse = Exit;
        } else if (c == 'S') {// sword
            picToUse = Sword;
        } else if (c == 'A') {// armour
            picToUse = Armor;
        } else if (c == 'L') {// lantern
            picToUse = Lantern;
        } else if (c == 'H') {// health
            picToUse = Health;
        }
    }    

    JLabel[][] displayLabels = new JLabel[5][5];
    for (int i = 0, k = 0; i <= 4; i++, k = k + 80) {
        for (int j = 0, l = 0; j <= 4; j++, l = l + 80) {
            displayLabels[i][j] = new JLabel(picToUse,JLabel.CENTER);
            displayLabels[i][j].setBounds(l, k, 85, 85);
            displayPanel.add(displayLabels[i][j]);
        }
    }
}

您可能还希望将picToUse变量设置为5x5数组

假设字符串的长度为25,数组中的每个单元格都有一个字符串,则会得到以下结果:

ImageIcon[][] picToUse = new ImageIcon[5][5];
...
for (int x = 0; x < text.length(); x++){
    char c = text.charAt(x);
    if (c == 'X') {// can't see
        picToUse[x/5][x%5] = OuterWall;
    } else ...
}

但是如何在网格中创建jlabel呢?还是我不需要?
displayLabels[i][j] = new JLabel(picToUse[i][j], JLabel.CENTER);