Java Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

Phil picture Phil · Mar 22, 2013 · Viewed 68.7k times · Source

OK what I am trying to do here is create a game where the object/ball is controlled by clicking on the object with the mouse, pulling back the mouse (the distance the mouse is pulled back will determine the velocity of the object) and on releasing the button the object will move (it's angle of movement will also be determined by the angle the mouse was pulled back)

Now as far as I can tell the 'math' at least should just about work, unfortunately I haven't been able to test that out as I'm getting the following error.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Snail.moveUp(Snail.java:35)
at Snail.chill(Snail.java:20)
at Level.mouseReleased(Level.java:120)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

From what i understand this means that i may have declared something which has a null value, but this is confusing me as i have done printouts of all my variables and all are giving values.

I then assumed that perhaps i am telling the object to move before the value has been declared, but i can't figure out why that would be happening.

My Code is as follows.

import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.event.MouseInputListener;

@SuppressWarnings("serial")
public class Level extends JPanel implements ActionListener, MouseInputListener{

Timer time;
private Image i;
private Graphics doubleG;
Snail s, s2;

boolean canJump;
int sx2;
int sy2;
int sx3;
int sy3;
double clickX;
double clickY;
double relX;
double relY;
double angle;
double speed;
double distance;

double scalex;
double scaley;
double velocityx = 1;
double velocityy = 1;

public Level(){

    s = new Snail();
    setFocusable(true);

    addMouseListener(this);
    addMouseMotionListener(this);
    //s2 = new Snail(250, 250);
    time = new Timer(17, this);
    time.start();   
}

@Override //double buffer
    public void update(Graphics g) {
        super.update(g);
            if(i == null){
                i = createImage(this.getSize().width, this.getSize().height);
                doubleG = i.getGraphics();
            }

            doubleG.setColor(getBackground());
            doubleG.fillRect(0, 0, this.getSize().width, this.getSize().height);

            doubleG.setColor(getForeground());
            paint(doubleG);

            g.drawImage(i, 0, 0, this);
    }

public void actionPerformed(ActionEvent e){
    s.update(this);
    //s2.update(this);
    repaint();


}

public void paintComponent (Graphics g) {   super.paintComponent(g); 
    s.paint(g);
    //s2.paint(g);

}

@Override
public void mouseClicked(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent ep) {
    clickX = ep.getX();
    clickY = ep.getY();
}

@Override
public void mouseReleased(MouseEvent er) {
    relX = er.getX();
    relY = er.getY();
    angle = Math.toRadians(Math.atan2(clickY - relY, clickX - relX));

    distance = Math.hypot(relX-clickX, relY-clickY);
    speed = distance/8;

    scalex = Math.cos(angle);
    scaley = Math.sin(angle);
    velocityx = speed * scalex;
    velocityy = speed * scaley;

    if (speed > 20){
        speed = 20;
    }

    if (canJump) {s.moveUp();

    }

}

@Override
public void mouseDragged(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseMoved(MouseEvent em) {
    sx2 = s.x - s.radius;
    sy2 = s.y + s.radius;
    sx3 = s.x + s.radius;
    sy3 = s.y - s.radius;

    if (em.getX() >= sx2 && em.getX() <= sx3 && em.getY() >= sy3 && em.getY() <= sy2){
        canJump = true;
    }else{
        canJump = false;
    }
    System.out.println("Click   X " + clickX + " Click   Y " + clickY);
    System.out.println("Release X " + relX + " Release Y " + relY);
    System.out.println("angle" + angle);
    System.out.println("distance" + distance);
    System.out.println("velx " + velocityx);
    System.out.println("vely " + velocityy);
    System.out.println(scalex);
    System.out.println(scaley);
    System.out.println(" ");

}

}

This would be the second class to which the error seems to be occurring, i am calling on an instance variable from the class above.

import java.awt.Color;
import java.awt.Graphics;


public class Snail {

Level l;
private double gravity = 10;
private double energyloss = 0.6;
private double xFriction = .95;
private double dt = .2;
int x = 0;
int y = 0;
double dx = 0;
double dy = 0;
int radius = 30;


public void chill(){
    moveUp();
}

public Snail() {
    // TODO Auto-generated constructor stub
}

public Snail(int i, int j) {
    // TODO Auto-generated constructor stub
    x = i;
    y = j;
}

public void moveUp() {
        dx = dx + l.velocityx;
        dy = dy + l.velocityy;
} 

public void update(Level l){

    if (x + dx > l.getWidth() -radius){
        x = l.getWidth() -radius;
        dx = - dx;
    }else if( x + dx < 0 +radius){
        x = 0+radius;
        dx = -dx;
    }
    else{
        x += dx;
    }

    if(y == l.getHeight()-radius)
        dx *= xFriction;
    if (Math.abs(dx) < .9){
        dx = 0;
    }

    if (y > l.getHeight() -radius){
        y = l.getHeight() -radius;
        dy *= energyloss;
        dy = - dy;
    }else{
        //velocity formula
        dy = dy + gravity *dt;
        //position formula
        y += dy*dt + .5*gravity*dt*dt;
    }

}

public void paint(Graphics g){
    g.setColor(Color.RED);
    g.fillOval(x-radius, y-radius, radius*2, radius*2);
}

}

Finally the class that initialises the level.

import javax.swing.JFrame;

public class Frame {


public static void main(String[] args){
    JFrame frame = new JFrame("Hard as Snails");
    frame.add(new Level());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1280,720);
    frame.setVisible(true);

}

}

Could anyone help me on what i am doing wrong here, I am quite new too this level of coding so please explain as if talking to an idiot. Many thanks for your time!

Answer

Smit picture Smit · Mar 22, 2013

Your Level l object seems to be null. As you havent initialized it and you are trying to use it in moveUp() method throwing NullPointerException.

You should initialized it as follows.

 Level l = new Level();
  1. You should assign values double x = 1.0;. I can see double x = 1; everywhere which could give you unexpected results.