I am making a java game and I am getting the following error:
actionPerformedException in thread "AWT-EventQueue-0" java.lang.NullPointerException
at OurGame.Ball.checkCollision(Ball.java:53)
at OurGame.Ball.actionPerformed(Ball.java:57)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(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)
It is happening when my game checks for collision between the ball and my other object. This is my code for Ball.java:
package OurGame;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class Ball extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
int x, y, cx, cy;
Image img;
ImageIcon i;
Player p;
Board b;
Timer t;
Random r;
Rectangle player, ball;
public Ball() {
r = new Random();
x = 500;
y = 190;
cx = -1;
System.out.println("New coin created: " + x + ", " +y);
i = new ImageIcon("ball.png");
img = i.getImage();
t = new Timer(10,this);
t.start();
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.print("actionPerformed");
checkCollision();
move();
}
public void checkCollision(){
player = new Rectangle(p.getX(),p.getY(),10,32);
ball = new Rectangle(getX(),getY(),8,8);
if (player.intersects(ball))
{
// A Collision!
// we know which enemy (e), so we can call e.DoCollision();
b.score += 1;
if(cx == -1) {
cx = 1;
} else {
if(cx == 1) {
cx = -1;
}
}
System.out.println("Collided");
} else {
}
}
public void move() {
System.out.print("MOVING");
x += cx;
}
public void setX(int xs) {
x = xs;
}
public void setY(int ys) {
y = ys;
}
public Image getImage(){
return img;
}
public int getX(){
return x;
}
public int getY() {
return y;
}
}
The error is occurring at this piece of code:
player = new Rectangle(p.getX(),p.getY(),10,32);
Your
Ballclass has a field calledpthat is of typePlayer.But you never assign a value to that field, so it will always be
null.Trying to call any method on that
nullvalue will surely result in aNullPointerException.You either need to ensure that every
Ballhas aPlayerassigned (ideally during construction) or change your code to handle the lack of aPlayer(i.e. check fornullwhere appropriate).Also, the
Rectanglefieldsplayerandballonly seem to be used in thecheckCollisionmethod and therefore should be local variables declared in that method and not fields.