嗨,伙计们,我想遍历字符串参数,对于字符串中的每个字符,我想创建一个带有与字符串中特定字符匹配的图标的标签。我希望标签在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 ...
}
由于采用了整数运算,将范围[0,25)
变换为[0,5)x[0,5)
。
您可以使用将图像添加到标签中
displayLabels[i][j] = new JLabel(picToUse[i][j], JLabel.CENTER);