我很难找到为什么我在这段代码上返回空指针:
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) {
行上得到了一个空指针。我在另一个类中以samme方式使用.getWidth()
,它可以正常工作-但由于某种原因,它不会在此使用。我试过打印结果,但这只是另一个nullpointer。我知道我缺少某些东西,但找不到。 最佳答案
你不打电话
public void Ball(GameStart game) {
this.game = game;
}
因此,在您的
Move
类中,GameStart
仍然为空。关于java - 使用.getWidth()时找不到空指针的原因,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31053708/