gpt4 book ai didi

java - 使用.getWidth()时无法定位空指针的原因

转载 作者:行者123 更新时间:2023-12-01 06:50:34 25 4
gpt4 key购买 nike

我很难找到为什么这段代码返回空指针:

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

}

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);

}

}

}

我在 if (x + x_1 > game.getWidth() - DIAMETER) { 行上得到一个空指针。我在另一个类中以相同的方式使用 .getWidth() 并且它工作正常 - 但由于某种原因它不会在这个类中。我尝试打印结果,但这只是另一个空指针。我知道我丢失了一些东西,但我找不到它。

最佳答案

你没有打电话

public void Ball(GameStart game) {
this.game = game;
}

这就是为什么在您的 Move 类中,GameStart 仍然为 null。

关于java - 使用.getWidth()时无法定位空指针的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31053708/

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