使用字符串数组元素作为变量名?

Using an String array element as a variable name?

我正在尝试将许多图片导入可见的网格线以显示为条(确切地说是健康条),当受到损坏时该条会减少(添加白色图像代替条的位置)。所以我决定不为 10 个可能的健康点中的每一个写出大量代码(更不用说还有其他玩家统计数据将以相同的格式完成),我决定拼凑一个 "for" 循环两个 if-else 语句尝试循环填充每个网格元素,只要健康值大于 "for" 循环的 "i"。如果玩家恰好在 10 点达到最大生命值,则图像会略有不同,因此需要第二个 "if-else" 循环。<p> 我的主要问题是关于我的循环的名称,因为我使用了一个数组来充当我希望成为 ImageIcon 名称的字符串名称的一种持有者,但我未能正确安排代码或找到解释来源如何使用数组字符串名称作为 ImageIcon 的名称。

这是循环和数据:<p>

String[] array1 ={"hOne","hTwo","hThree","hFour","hFive","hSix","hSeven","hEight","hNine","hTen"};
    String tempY = " ", tempN = " ", tempF = " ", tempNF = " ";
        //row 1, health
        statsPanel.add(stat1);
    for (int i=0; i<=9; i++){
        if ((i+1)<heal){
        tempY=array1[i];
        ImageIcon tempY = new ImageIcon("C:\Users\Kunkle\hea.png");  
        ColorPanel tempYz = new ColorPanel(Color.black, tempY);
        statsPanel.add(tempYz);
            }
        else {
        tempN=array1[i];    
        ImageIcon tempN = new ImageIcon("C:\Users\Kunkle\non.png");  
        ColorPanel tempNz = new ColorPanel(Color.black, tempN);
        statsPanel.add(tempNz);
            }
        if (i==8 && heal==10){
        tempF=array1[i];
        ImageIcon tempF = new ImageIcon("C:\Users\Kunkle\shea.png");  
        ColorPanel tempFz = new ColorPanel(Color.black, tempF);
        statsPanel.add(tempFz);
            }
        else {
        tempNF=array1[i];   
        ImageIcon tempNF = new ImageIcon("C:\Users\Kunkle\shea.png");  
        ColorPanel tempNFz = new ColorPanel(Color.black, tempNF);
        statsPanel.add(tempNFz);
            }
}

一切都已正确声明为变量和导入方式,我得到的唯一 3 个错误是在每个新图像声明中的第一个 "ImageIcon" 之后声明数组元素的四行。是否有一种方法可以通过 "for" 循环(或多个循环)来保持代码简短,但仍然会在每次传递时以新名称引入图像?

你不能做你想做的事。 Java 不是一种可以用变量值代替名称的动态语言,这是一种 Perl,其中 $x="a"; $$x=3; 导致变量 $a 具有值 3.

最接近的做法是使用 Map<String,ImageIcon> 将字符串与对象相关联。如果你想将 ImageIconColorPanel 都与一个名称相关联,你需要一个包装对象来保存对两者的引用,而你有一个 Map<String,MyWrapper>

我会提供代码示例,但这需要查看您尚未提供的 statsPanel 的代码。我的猜测是 statsPanel 将是(或包含)我上面提到的 Map<>