gpt4 book ai didi

java - 这个演示五分之四有效,为什么有时会出现错误?

转载 作者:行者123 更新时间:2023-12-02 08:16:06 24 4
gpt4 key购买 nike

我正在练习渲染和绘制图形,我似乎无法找出为什么 eclipse 在大约 1/5 的时间里给我一个错误。

Exception in thread "Thread-3" java.lang.NullPointerException
at game.StartingPoint.run(StartingPoint.java:74)
at java.lang.Thread.run(Unknown Source)

是我的线程有问题吗?我该如何解决这个问题?

这是我的源代码。

StartingPoint.java:

package game;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;

public class StartingPoint extends Applet implements Runnable {

Image i;
Graphics doubleG;
Ball b1;
Ball b2;

public StartingPoint() {

}

@Override
public void init() {

}

@Override
public void start() {

setSize(480, 360);

Thread thread = new Thread(this);
thread.start();

b1 = new Ball(40, 40);
b2 = new Ball(70, 200);

}

@Override
public void stop() {

}

@Override
public void destroy() {

}

@Override
public void update(Graphics g) {

if (i == null) {
i = createImage(this.getWidth(), this.getHeight());
doubleG = i.getGraphics();
}
doubleG.setColor(getBackground());
doubleG.fillRect(0, 0, this.getWidth(), this.getHeight());

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

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

@Override
public void paint(Graphics g) {
b1.paint(g);
b2.paint(g);

}

@Override
public void run() {
while (true) {

b1.update(this);
b2.update(this);

repaint();
try {
Thread.sleep(30);
} catch (Exception e) {

System.out.print("Error");

}
}

}
}

Ball.java:

package game;

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

public class Ball {
double gravity = 15.0;
double energyLoss = .65;
double outsideEnergy = .95;
double dt = .25;
double xFriction = .9;
int x = 40;
int y = 40;
double dx = 7.0;
double dy = 0.0;
int radius = 20;

public Ball() {

}

public Ball(int x, int y) {

this.x = x;
this.y = y;

}

public void update(StartingPoint sp) {
if (x <= 0 | x >= sp.getWidth()) {
dx = -dx;
}

if (y > sp.getHeight() - radius - 1) {
y = sp.getHeight() - radius - 1;
dy *= energyLoss;
dy = -dy;
dx *= outsideEnergy;
} else {
// velocity
dy = dy + gravity * dt;
// d=viT + 1/2(a)t^2
y += dy * dt + .5 * gravity * dt * dt;

}

x += dx;
}

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

}
}

最佳答案

看看

Thread thread = new Thread(this);
thread.start();

b1 = new Ball(40, 40);
b2 = new Ball(70, 200);

您正在线程启动后初始化变量。有时线程在它们实际初始化之前使用它们,有时它们首先被初始化。将它们移到 start() 调用之前:

b1 = new Ball(40, 40);
b2 = new Ball(70, 200);

Thread thread = new Thread(this);
thread.start();

关于java - 这个演示五分之四有效,为什么有时会出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17686150/

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