Evi*_*ill 0 java nullpointerexception null-pointer
我很难找到为什么我在这段代码上返回nullpointer:
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Move {
private static final int DIAMETER = 30;
int x = 0;
int y = 0;
int x_1 = 1;
int y_1 = 1;
private GameStart game;
public void Ball(GameStart game) {
this.game = game;
}
void moveBall() {
if (x + x_1 < 0) {
x_1 = 1;
}
if (x + x_1 > game.getWidth() - DIAMETER) {
x_1 = -1;
}
if (y + y_1 < 0) {
y_1 = 1;
}
if (y + y_1 > game.getHeight() - DIAMETER) {
game.gameOver();
}
if (collision()) {
y_1 = -1;
y = game.racquet.getTopY() - DIAMETER;
}
x = x + x_1;
y = y + y_1;
}
private boolean collision() {
return game.racquet.getBounds().intersects(getBounds());
}
public void paint(Graphics2D g) {
g.fillOval(x, y, 30, 30);
}
public Rectangle getBounds() {
return new Rectangle(x, y, DIAMETER, DIAMETER);
}
}
Run Code Online (Sandbox Code Playgroud)
GameStart类在这里:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
@SuppressWarnings("serial")
public class GameStart extends JPanel {
Move move_ball = new Move();
Racquet racquet = new Racquet(this);
public GameStart() {
addKeyListener(new MyKeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
racquet.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
racquet.keyPressed(e);
}
});
setFocusable(true);
}
private void move() {
move_ball.moveBall();
racquet.move();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D graphics = (Graphics2D) g;
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
move_ball.paint(graphics);
racquet.paint(graphics);
}
public void gameOver() {
JOptionPane.showMessageDialog(this, "Spil slut", "Du tabte", JOptionPane.YES_NO_OPTION);
System.exit(ABORT);
}
public static void main (String[] args) throws InterruptedException {
JFrame mainWindow = new JFrame("Matematikken");
GameStart game = new GameStart();
mainWindow.add(game);
mainWindow.setSize(300, 400);
mainWindow.setVisible(true);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
Thread.sleep(10);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在线上得到了一个nullpointer if (x + x_1 > game.getWidth() - DIAMETER) {.我.getWidth()在另一个班级使用samme方式,它工作正常 - 但由于某种原因它不会在这.我已经尝试打印结果,但这只是另一个nullpointer.我知道我错过了一些东西,但我无法找到它.
你不打电话
public void Ball(GameStart game) {
this.game = game;
}
Run Code Online (Sandbox Code Playgroud)
这就是为什么在你的Move课堂上,GameStart仍然是空的.