final Icon[] landIcons = {
/* for(int i=0, i<15, i++)
{
new ImageIcon(getClass().getResource(landNames[i]));
}
}*/
new ImageIcon(getClass().getResource(landNames[0])),
new ImageIcon(getClass().getResource(landNames[1])),
new ImageIcon(getClass().getResource(landNames[2])),
new ImageIcon(getClass().getResource(landNames[3])),
new ImageIcon(getClass().getResource(landNames[4])),
new ImageIcon(getClass().getResource(landNames[5])),
new ImageIcon(getClass().getResource(landNames[6])),
new ImageIcon(getClass().getResource(landNames[7])),
new ImageIcon(getClass().getResource(landNames[8])),
new ImageIcon(getClass().getResource(landNames[9])),
new ImageIcon(getClass().getResource(landNames[10])),
new ImageIcon(getClass().getResource(landNames[11])),
new ImageIcon(getClass().getResource(landNames[12])),
new ImageIcon(getClass().getResource(landNames[13])),
new ImageIcon(getClass().getResource(landNames[14]))};
我创建了一个图标数组,并在注释中添加了循环每个元素的想法。我不能说为什么它在 for 循环中不起作用。还有其他方法可以缩短所有这些代码吗?谢谢!
最佳答案
它不起作用,因为它是非法语法。
final Icon[] landIcons = {
for(int i=0, i<15, i++)
{
new ImageIcon(getClass().getResource(landNames[i]));
}
}
不能在数组初始化 block 内运行循环
使用这个:
final Icon[] landIcons = new Icon[15];
for(int i=0, i<landIcons.length , i++)
{
landIcons[i] = new ImageIcon(getClass().getResource(landNames[i]));
}
关于java - 有没有更有效的方法来编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36168241/