线程中的异常" AWT-EventQueue-0"显示java.lang.NullPointerException 在Snooker.paint(Snooker.java:34)
这是我所得到的错误。
以下是代码:
主类:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Snooker extends JPanel {
public static final int WIDTH = 900;
public static final int HEIGHT = 450;
public static final Color c = Color.black;
public static final int SIZE_ball = 10;
private Table table;
private Ball ball;
private Cue cue;
public Snooker() {
table = new Table(0,0,c,WIDTH,HEIGHT);
ball = new Ball(150,150,Color.RED,SIZE_ball);
}
public void paint(Graphics g) {
super.paint(g);
table.drawTableOn(g);
ball.drawBallOn(g);
cue.drawCueOn(g);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Snooker");
frame.setLayout(new BorderLayout());
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Snooker game = new Snooker();
frame.add(game);
frame.setVisible(true);
game.requestFocusInWindow();
}
}
图形类:
import java.awt.Color;
import java.awt.Graphics;
public class GraphicsItem {
protected int x,y;
protected Color color;
private static final int SIZE_tableX = 900;
private static final int SIZE_Cue = 30;
public static final int R_ball = 5;
public static int CoorY = 150;
public static int CoorX = 150;
public GraphicsItem(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void moveBallBy(int dx, int dy) {
x += dx;
y += dy;
}
public void drawTableOn(Graphics g) {
g.setColor(color.BLACK);
g.fillRect(x, y, SIZE_tableX, SIZE_tableX/2);
}
public void drawBallOn(Graphics g) {
g.setColor(color.BLACK);
g.fillOval(x,y,R_ball,R_ball);
}
public void drawCueOn(Graphics g) {
g.setColor(color.BLACK);
g.drawLine(x,y,SIZE_Cue,SIZE_Cue);
}
}
还有5个班级。 Cue,Ball,Table和CueBall(extends Ball),BroadCloth(扩展表)。他们的对象只有态度。
建议解决?
答案 0 :(得分:1)
你必须在类Snooker的构造函数中初始化cue。
你的构造函数应该是:
public Snooker() {
table = new Table(0,0,c,WIDTH,HEIGHT);
ball = new Ball(150,150,Color.RED,SIZE_ball);
cue = new Cue( ... );
}
就目前而言,cue尚未实例化,并在您尝试访问其方法时抛出NullPointerException。