2015-05-04 36 views
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; 
      } 
     } 
    } 
+0

注意:不要調用Polyingon'P'。只有類型名稱在開頭應該有一個大寫字母(而常量是全部大寫)。字段,局部變量和方法應該以小寫字母開頭。 – RealSkeptic

+0

您可能想了解一下[使用幾何圖形](https://docs.oracle.com/javase/tutorial/2d/geometry/index.html) – MadProgrammer

回答

2

您申報poligon但不創建對象。這種方式在Pizza的構造函數中使用它時爲null。在構造函數中使用它之前,您將需要創建一個實例。另外P是變量的錯誤名稱

public Pizza(int x, int y) { 
     super(x,y); 
     //P is null here - add P=new Poligon() 
     P.xpoints = new int[]{x, x+100, x+200}; 
     P.ypoints = new int[]{y, y+100, y}; 
     P.npoints = 3; 
    } 
0

你沒有初始化PolygonP。 試試這個:

public Pizza(int x, int y) { 
    super(x,y); 
    P = new Polygon(); 
    P.xpoints = new int[]{x, x+100, x+200}; 
    P.ypoints = new int[]{y, y+100, y}; 
    P.npoints = 3; 
}