Jonathan Jonathan - 2 months ago 7
Java Question

NullPointerException when using mouseClicked on very simple code

Edit: I understand what a NPE error is, I was struggling to find which part of my code was producing it.

I'm very new to java and a lot of the coding on here flies way over my head.

I've been trying to implement a very simple program that simply makes a stick figure jump when you click the canvas but it's been throwing up a NullPointerException when attempting to click the canvas.

I fully understand that the functions and implementation I use below are far from optimal but I'm just trying to apply the very basics I've picked up, walking before flying and all that, and so whilst I'll happily take advice on how to improve the general implementation what I'm really after is just how to solve the current error, thanks!.

import comp102x.Canvas;
import comp102x.ColorImage;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class JumpMan implements MouseListener {
private Canvas canvas;
public ColorImage jumpMan;

public JumpMan()
{
canvas = new Canvas();
canvas.addMouseListener(this);
ColorImage jumpMan = new ColorImage("jumpmanimg.png");
canvas.add(jumpMan,200,200);
}


public void mouseClicked(MouseEvent click)
{
for (int i=1; i<=50; i++)
{
jumpMan.setY(jumpMan.getY()+1);
pause(2);
}
for (int i=50; i>=0; i--)
{
jumpMan.setY(jumpMan.getY()-1);
pause(2);
}
}

private void pause(int sleepTime) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
System.exit(-1);
}
}
public void mousePressed(MouseEvent click){}
public void mouseReleased(MouseEvent click){}
public void mouseEntered(MouseEvent click){}
public void mouseExited(MouseEvent click){}
}

Answer

Change your code to this -

private Canvas canvas;
public ColorImage jumpMan;

public JumpMan()
{
    canvas = new Canvas();
    canvas.addMouseListener(this);
    jumpMan = new ColorImage("jumpmanimg.png");
    canvas.add(jumpMan,200,200);
}

Now it will be ok....

Comments