2014-10-11 53 views
-4

新手Java程序员在这里(2周)从学校得到一份任务来创建一个Sierpinski三角形程序。JAVA:我不明白这个NullPointerException

处理绘图的代码已经存在,我只需创建表示顶点和三角形的对象以及划分三角形的方法。我做了所有这些,但调用应该绘制三角形的方法给了我一个NullPointerException,我不知道是什么导致了它。

我不能分享我的代码,可能会导致我自动故障的过程中,但在这里,让我错误的预先写好的方法:

public boolean paintTriangle(Triangle triangle) { 
    int width = panel.getWidth(); 
    int height = panel.getHeight(); 
    int halfX = width/2; 
    int halfY = height/2; 

    Vertex2D a = triangle.getVertexA(); 
    Vertex2D b = triangle.getVertexB(); 
    Vertex2D c = triangle.getVertexC(); 

    int minX = width - ((int) Math.rint(halfX - Math.min(a.getX(), Math.min(b.getX(), c.getX())))); //this is where I get the nullPointerException 
    int maxX = width - ((int) Math.rint(halfX - Math.max(a.getX(), Math.max(b.getX(), c.getX())))); 
    int minY = (int) Math.rint(halfY - Math.min(a.getY(), Math.min(b.getY(), c.getY()))); 
    int maxY = (int) Math.rint(halfY - Math.max(a.getY(), Math.max(b.getY(), c.getY()))); 

    if (minX < 0 || maxX > width || minY < 0 || maxY > height) { 
     return false; 
    } 
    triangles.add(triangle); 
    return true; 
} 

我敢肯定,我的getX和的getY方法正确。

感谢您对我英文不熟悉的帮助和歉意。

+1

什么是异常栈跟踪说?有几件事可以为空 - >检查面板,三角形,a,b,c和三角形。 – brianestey 2014-10-11 16:40:17

+4

你看过[什么是空指针异常,我该如何解决它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -我修复它) – 2014-10-11 16:41:11

回答

0

这些都是所有的事情,可以在你的代码是空的列表:

  1. 三角
  2. 面板
  3. 一个
  4. b
  5. Ç

最佳猜测会是a,b或c是null,因此a.getX(),b.getX()或c.getX()可能是throwi ng NullPointerException

0

¿您是否在传递intantialize并初始化三角形对象?

喜欢的东西:

Triangle triangle = new Triangle(); 

Vertex2D vertexA = new Vertex2D(); 
vertexA.setX(x); // x and y are numeric primitives 
vertexA.setY(y); 

Vertex2D vertexB = new Vertex2D(); 
vertexB.setX(x); 
vertexB.setY(y); 

Vertex2D vertexC = new Vertex2D(); 
vertexC.setX(x); 
vertexC.setY(y); 

triangle.setVertexA(vertexA); 
triangle.setVertexB(vertexB); 
triangle.setVertexC(vertexC); 

paintTriangle(triangle); 

在另一方面,也许你没有正确创建面板对象。

JPanel panel = new JPanel(); 
panel.setPreferredSize(new Dimension(800,600))