有没有更有效的方法来编码?

时间:2016-03-23 01:26:22

标签: java arrays icons imageicon

    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循环中不起作用。还有另一种缩短所有代码的方法吗?谢谢!

2 个答案:

答案 0 :(得分:1)

它不起作用bcoz这是非法语法。

final Icon[] landIcons = {
        for(int i=0, i<15, i++)
          {
             new ImageIcon(getClass().getResource(landNames[i]));
          }
      }

你不能在数组初始化块

中运行循环

使用它:

  final Icon[] landIcons = new Icon[15];
  for(int i=0, i<landIcons.length , i++)
    {
       landIcons[i] = new ImageIcon(getClass().getResource(landNames[i]));
    }

答案 1 :(得分:0)

您可以使用List来保存项目,以便您可以使用循环将ImageIcon添加到该列表。如果确实需要数组,请在该List上调用toArray()。