gpt4 book ai didi

Java 代码 - NullPointerException

转载 作者:行者123 更新时间:2023-11-29 09:45:33 25 4
gpt4 key购买 nike

我正在制作一个游戏,它给了我一个 NullPointerException,我认为这意味着变量或我正在尝试做的事情没有返回值?我正在使用下面的代码:

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;
Random 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;
}


}

错误发生在这里:

        setX(r.nextInt(640));

完整的错误输出如下:

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)

我看不出有任何原因会发生这种情况,但也许您可以提供帮助。

谢谢。

最佳答案

你正在使用 r 而没有说 r = new ...

关于Java 代码 - NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7631406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com