Java:在类实例上调用时,不能从静态上下文引用非静态变量

时间:2016-01-30 19:30:47

标签: java bufferedimage

注意:这不是像this这样的问题的重复,因为它们试图在类上调用实例方法,而不是实例。我的意思是我试图在一个实例上调用一个实例方法,它仍然会给出错误。

我在尝试在类上调用实例方法时遇到了经典错误。我的问题是我试图在一个实例上调用一个实例方法而且我得到了这个错误。我的代码是:

public class PixelsManipulation{

// Load in the image
private final BufferedImage img = getImage("strawberry.jpg");
Sequential sequentialGrayscaler = new Sequential(img, 2, 2);//img.getWidth(),img.getHeight());

public static void main(String[] args) {  

    // Sequential:
    long startTime = System.currentTimeMillis();

    sequentialGrayscaler.ConvertToGrayscale(); // error here
    // ... etc.
}

为什么会发生这种情况?我有没有错过的东西?我已经声明了一个名为sequentialGrayscaler的Sequential实例,我试图在它上面调用.ConvertToGrayscale(),而不是类本身。

顺序代码只是:

public class Sequential {
private int width, height; // Image params
private BufferedImage img;

// SEQUENTIAL
// Load an image from file into the code so we can do things to it

Sequential(BufferedImage image, int imageWidth, int imageHeight){
    img = image;
    width = imageWidth;
    height = imageHeight;
}

public void ConvertToGrayscale(){
// etc.

编辑:如果我注释掉图像并使用整数参数实例化Sequential对象,它就可以了。所以问题必须与BufferedImage有关。

以下是我用来读取图片的代码:

private static BufferedImage getImage(String filename) {
    try {
        InputStream in = getClass().getResourceAsStream(filename); // now the error is here
        return ImageIO.read(in);
    } catch (IOException e) {
        System.out.println("The image was not loaded. Is it there? Is the filepath correct?");
        System.exit(1);
    }
    return null;
}

我可以追逐的最后一个地方"追逐"错误是我创建InputStream的行。那里的错误是#34;非静态方法getClass()不能从静态上下文引用"。这是在将Sequential声明与ConvertToGrayscale()方法一起设置为静态之后。这是在说:

private static BufferedImage img = getImage("strawberry.jpg");
private static Sequential sequentialGrayscaler = new Sequential(img, 2, 2);

并且使getImage()也是静态的(必须这样做,否则当我尝试创建BufferedImage时会出现错误)。

编辑:最后我只需要将我的getImage()方法移出主类并进入Sequential类。理想情况下,我不想这样做,因为它可能意味着如果我想在其他类中实现它们,我会有很多重复的getImage()方法,但至少它现在可以工作。

1 个答案:

答案 0 :(得分:1)

这是因为sequentialGrayscaler类的PixelsManipulationprivate static BufferedImage img = getImage("strawberry.jpg"); private static Sequential sequentialGrayscaler = new Sequential(img, 2, 2); 对象都是非静态的。将它们更改为静态。

getClass().getResourceAsStream(...)

此外,您无法通过静态方法执行public class PixelsManipulation { /* Your Code Here */ private static BufferedImage getImage(String filename) { try { /* Code Change */ InputStream in = PixelsManipulation.class.getResourceAsStream(filename); return ImageIO.read(in); } catch (IOException e) { System.out.println("The image was not loaded. Is it there? Is the filepath correct?"); System.exit(1); } return null; } } 。请改用该类的名称。

current

执行这些更改后,它应该可以正常工作。