0
当我想绘制我的多边形Pizza
对象时,我总是收到一个NullPointerException异常。我得到这个错误信息:Java JFrame /图形驱动程序
Exception in thread "main" java.lang.NullPointerException
at Pizza.<init>(Pizza.java:9)
at PolyDemo$PolyDemoPanel.getRandShape(PolyDemo.java:91)
at PolyDemo$PolyDemoPanel.<init>(PolyDemo.java:54)
at PolyDemo.<init>(PolyDemo.java:19)
at PolyDemo.main(PolyDemo.java:28)
我没有用圆形和矩形的问题,这是为什么不工作?这里是我的比萨类:
import java.awt.*;
public class Pizza extends Shape{
private Polygon P;
public Pizza(int x, int y) {
super(x,y);
P.xpoints = new int[]{x, x+100, x+200};
P.ypoints = new int[]{y, y+100, y};
P.npoints = 3;
}
@Override
public void draw(Graphics g){
g.setColor(Color.RED);
g.drawPolygon(P);
}
}
这里是驱动程序:
import java.util.*;
import java.awt.*;
import javax.swing.*;
class PolyDemo extends JFrame {
public PolyDemo() {
getContentPane().add(new PolyDemoPanel());
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
PolyDemo myApp = new PolyDemo();
}
public class PolyDemoPanel extends JPanel {
Shape[] myShapes= new Shape[20];
public PolyDemoPanel() {
for(int i = 0; i < 20; i++) {
myShapes[i] = getRandShape();
}
}
public void paint(Graphics g) {
super.paint(g);
for(int i = 0; i < myShapes.length; i++){
myShapes[i].draw(g);
}
}
public int getRandInt() {
return ((int) (Math.random() * 200));
}
public Shape getRandShape() {
Shape retVal = null;
final int x = getRandInt();
final int y = getRandInt();
retVal = new Pizza(x, y);
return retVal;
}
}
}
注意:不要调用Polyingon'P'。只有类型名称在开头应该有一个大写字母(而常量是全部大写)。字段,局部变量和方法应该以小写字母开头。 – RealSkeptic
您可能想了解一下[使用几何图形](https://docs.oracle.com/javase/tutorial/2d/geometry/index.html) – MadProgrammer