Java Code - NullPointerException
I'm making a game and it is giving me a NullPointerException
which I believe means the variable or what I'm trying to do is not returning a value? I'm using the code below:
package OurGame;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Coin extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
Image img;
int x,y;
Timer t;
R开发者_如何学编程andom r;
public Coin() {
x = 50;
y = 50;
System.out.println("New coin created: " + x + ", " +y);
ImageIcon i = new ImageIcon("C:/coin.png");
img = i.getImage();
System.out.println(i);
t = new Timer(3000,this);
t.start();
}
@Override
public void actionPerformed(ActionEvent arg0) {
move();
}
public void move() {
setX(r.nextInt(640));
setY(r.nextInt(480));
}
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 happening here:
setX(r.nextInt(640));
The full error output is below:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at OurGame.Coin.move(Coin.java:46)
at OurGame.Coin.actionPerformed(Coin.java:40)
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)
I dont see any reason for this to happen but maybe you can help.
Thanks.
You are using r
without ever saying r = new ...
.
You need to initialise the variable r
. Check out the constructors for java.util.Random
, for example:
Random r = new Random();
r
is null. Initialize it first. Put this in your constructor:
r = new Random();
精彩评论