gpt4 book ai didi

java - 空点异常,不知道为什么?

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

<分区>

好的,我是 Java 的半新手,我正在制作乒乓球游戏。我想完全自己做,但我遇到了一个问题。到目前为止,我已经上了 2 节课。我的主要一个,其中包含有关球的信息。我的主类如下:

    import java.awt.Canvas;
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;


public class Main extends Canvas implements Runnable{

private static final long serialVersionUID = 1L;

public static int Width=800;
public static int Height=600;
public boolean Running=false;
public Thread thread;
public Ball ball;
public int BallX = ball.BallLocationX;
public int BallY = ball.BallLocationY;



public static void main(String[] args){
Main game = new Main();
JFrame frame = new JFrame();
frame.setSize(Width, Height);
frame.setTitle("Pong By Poo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.add(game);
game.start();
}


public void start(){
if(Running==true){
return;
}
else {
Running=true;
thread = new Thread(this);
thread.start();
}
}



public void run(){
while(Running==true){
Draw();
}

}

public void Draw(){
BufferStrategy bs = this.getBufferStrategy();
if(bs==null){
createBufferStrategy(2);
}else{
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillOval(BallX, BallY, 10, 10);
}


}

}

我的球类是这样的:

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

import javax.swing.JPanel;

public class Ball extends JPanel{
public int BallLocationX;
public int BallLocationY;
public boolean BallMovementY; //true makes the ball go up, false makes it go down
public boolean BallMovementX; //True makes the ball go right, false makes it go left.

public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(BallLocationX, BallLocationY, 10, 10);
}

//moves the ball left to right
public int YVelocity(){

if(BallMovementY==true){
BallLocationY++;
}
else{
BallLocationY--;
}

return BallLocationY;

}

//Moves the ball up and down
public int XVelocity(){

if(BallMovementX==true){
BallLocationX++;
}
else{
BallLocationX--;
}

return BallLocationX;

}
}
**

我试图在我的主类中的屏幕上绘制球,使用我从球类获得的球的位置。我知道(到目前为止)球不会移动,我稍后会弄清楚。我的问题是它不会在屏幕上绘制球,导致出现此错误:

Exception in thread "main" java.lang.NullPointerException
at Main.<init>(Main.java:20)
at Main.main(Main.java:26)

谢谢!

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