开发者

looping through each array to create shapes

I'm trying to make the paintCOmponent method loop through each element of an array and call a display method, so far i did this

public void paintComponent (Graphics g)
    {
      super.paintComponent(g); 
      for(int i = 0; i < drawObjects.length; i++){
        drawObjects[i].display(g);
      }
  }

I also tried a for each loop

public void paintComponent (Graphics g)
        {
          super.paintComponent(g); 
          for(Shape s : drawObjects)
           s.displ开发者_如何转开发ay(g);
         }

I get this error with both

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at ShapePanel.paintComponent(ShapePanel.java:70)

Could anyone explain to me what am i doing wrong?


You created an array without filling it in completely. When you create an array, it's full of nulls, and when you try to use the . operator on null, you get the NullPointerException. You either need to make sure the array is fully populated before trying to iterate over it or else add a null check inside the loop so you only try to display() the thing if it's not null.

If you really have a variable number of things to display, you should consider using some kind of List, like an ArrayList, rather than an array, as Lists can vary in size and won't contain a null unless you put one there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜