BufferedImage数组对值集显示为null

时间:2014-10-10 08:57:48

标签: java java-ee

在类getPathGiveIcon中,我将一个字符串数组传递给getPaths()方法。这个getPaths()应该返回一个ImageIcons数组。在这个过程中,我试图从字符串数组中的每个路径名创建一个文件,但是在这一行出现错误。 img [i] = ImageIO.read(fa); //在此行中出错 请指导我过来这个错误...

以下是getPaths()方法的完整代码。

public class GetPathGiveIcon {
ImageIcon[] iic;
File f = new File(" ");
int i = 0;


public ImageIcon[] getPaths(String[] s)
{

   BufferedImage[] img = null; 

   for(String st : s)
   {
       System.out.println(st);
   }

   for(String st : s)
    try
    {
        {
            File fa = new File(st);
            img[i] = ImageIO.read(fa);
            System.out.println(" inside try block the value of every string = " + st);
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

   System.out.println(" Value of I before scaling " + i);
   i = 0;
   for(BufferedImage bi : img)
   {
       iic[i] = new ImageIcon(bi);
       Image scaled = iic[i].getImage().getScaledInstance(150,150, 
Image.SCALE_DEFAULT);
       iic[i] = new ImageIcon(scaled);
       i++;
   }
   System.out.println(" Value of I after scaling " + i);
   return iic;
}

}

2 个答案:

答案 0 :(得分:1)

那是因为

BufferedImage[] img = null; 

您必须使用

初始化img数组
BufferedImage[] img = new BufferedImage[s.length]; 

答案 1 :(得分:0)

我总是等于0,所以你的代码只会填充数组的第一个元素。

以下是解决方案:

BufferedImage[] img = new BufferedImage[s.length]; 

for(String st : s)
{
    try
    {
        File fa = new File(st);
        img[i++] = ImageIO.read(fa);
        System.out.println(" inside try block the value of every string = " + st);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

修改

iic相同的问题,必须初始化

iic = new ImageIcon[img.length];
i = 0;
for(BufferedImage bi : img)
{
   iic[i] = new ImageIcon(bi);
   // [...]