Note: This is not a duplicate of questions like this, because those are trying to call instance methods on classes, and not instances. Mine is that I'm trying to call an instance method on an instance and it still gives the error.
I'm getting the classic error that happens when you try to call an instance method on a class. My problem is that I'm trying to call an instance method on an instance and I'm getting that error. My code is:
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.
}
Why might this be happening? Is there something really obvious I've missed? I have declared an instance of Sequential called sequentialGrayscaler, and I'm trying to call .ConvertToGrayscale() on it, not the class itself.
The Sequential code is just:
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.
EDIT: If I comment out the image and just instantiate the Sequential object with integer params, it works. So the problem must be something to do with the BufferedImage.
Here is the code I use to read in images:
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;
}
The last place I can "chase" the error to is the line where I create an InputStream. The error there is "non static method getClass() cannot be referenced from a static context". This is after making the Sequential declaration static along with the ConvertToGrayscale() method. This is after saying:
private static BufferedImage img = getImage("strawberry.jpg");
private static Sequential sequentialGrayscaler = new Sequential(img, 2, 2);
And making getImage() static as well (have to do that otherwise I get the error when I try and create the BufferedImage).
EDIT: Ultimately I just had to move my getImage() method out of my main class and into the Sequential class. Ideally I didn't want to do this since it probably means I'll have a lot of duplicate getImage() methods if I want to implement them in other classes, but at least it works for now.