NullPointerException(帮助!)

时间:2013-03-19 20:34:37

标签: java nullpointerexception

我一直在使用bookClasses类来操作图像,我在尝试去除图像中的红眼时遇到NullPointerException错误。这是代码:

首先是Picture.Java类中的removeRedEye方法:

 public void removeRedEye(int startX, int startY, int endX, int endY, Color newColor){

    Pixel pixel = null;

    for (int x = startX; x < endX; x++){
        for (int y = startY; y < endY; y++){
            if (pixel.colorDistance(Color.RED) < 167){
                        pixel.setColor(newColor);
            }
        }
    }
  }
}

和测试类:

public class TestRemoveRedEye{

    public static void main(String[] args){

        String fileName = FileChooser.getMediaPath("//jenny-red.jpg");

        Picture jennyPicture = new Picture(fileName);

        jennyPicture.removeRedEye(109,91,202,107,java.awt.Color.BLACK); 

        jennyPicture.explore();

    }
}

如果有人能说明为什么我的计划没有工作,我们将不胜感激。

这些行在错误中被挑选出来: 来自removeRedEye方法的if (pixel.colorDistance(Color.RED) < 167){

来自测试类的

jennyPicture.removeRedEye(109,91,202,107,java.awt.Color.BLACK);

2 个答案:

答案 0 :(得分:2)

像素 null 您需要在调用其引用方法之前对其进行初始化。

Pixel pixel = null;// neew to initialize this.
pixel = new Pixel(); // somethin like this 
for (int x = startX; x < endX; x++){
    for (int y = startY; y < endY; y++){
        if (pixel.colorDistance(Color.RED) < 167){

答案 1 :(得分:1)

您为pixel指定了null,并在之后调用了一个方法。因此NPE。

Pixel pixel = null;
for (int x = startX; x < endX; x++){
    for (int y = startY; y < endY; y++){
        if (pixel.colorDistance(Color.RED) < 167){ // <==== pixel is null !
                    pixel.setColor(newColor);
        }
    }
}