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

标签 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 循环中不起作用。还有其他方法可以缩短所有这些代码吗?谢谢!

最佳答案

它不起作用,因为它是非法语法。

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/

相关文章:

java - 如何在 Spark 2.4 中加载自定义变压器

java - 如何使用 JavaFX 在 Z 维度上定位形状

java - WindowBuilder Pro VS Matisse 4 MyEclipse

c - 错误 : array type has incomplete element type; dynamic 2D array

php - 如何在 PHP 中使用变量名创建新变量?

java - 根据深度级别更改 JTree 节点图标

java - Spring、Tomcat7中的全局异常处理

javascript - 在数组中创建计数元素的数组

c# - 基于定义C#更改exe图标

swing - JRadioButton MenuItem 中各种尺寸图标的垂直对齐