【问题标题】:ArrayList causing NullPointerExceptionArrayList 导致 NullPointerException
【发布时间】:2013-01-29 10:16:00
【问题描述】:

我从paintcomponent方法中得到了这段代码的空指针异常

  public A1Panel() {
            final ArrayList<MySnowFlake> myShapes = new ArrayList<MySnowFlake>();   //Stage 1: Replace this line
            popup = new JPopupMenu();               //create the popup menu
            makePopupMenu();

            addMouseListener( new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                maybeShowPopup(e);
            }

            public void mouseReleased(MouseEvent e) {
                maybeShowPopup(e);
            }

            private void maybeShowPopup(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    popup.show(e.getComponent(), e.getX(), e.getY());
                }
            }
            public void mouseClicked( MouseEvent e ) {  //Stage 1: Modify the following statements
                myShapes.add(currentIndex, new MySnowFlake(e.getX(), e.getY(), currentLevel, currentLength));
                currentIndex += 1;
                repaint();
            }
            });
        }

        public void paintComponent(Graphics g) {
                //g.drawString("" + currentIndex, 50,50);
            //Stage 1: Modify the following statements
            try{
            for (int i = 0; i < currentIndex; i++) {
                myShapes.get(i).paint(g);
            }
            } catch(NullPointerException e){
                System.out.println("NullPointerException caught!!");
            }
        }

我的雪花

public class MySnowFlake {
    protected int level;            // the recursion level
    protected Turtle turtle;        // the turtle object
    protected double turn = Math.PI/3; // the turning angle
    public int length;              // the length of the snowflake
    public Point p;                 // the initial position


    /** Constructor to create a Snowflake and initialize all values
    */
    public MySnowFlake(int x, int y, int level, int length) {
        this.level = level;
        this.length = length;
        p = new Point(x,y);
        turtle = new Turtle();
    }

    public void translate(int dx, int dy){
        p.x += dx;
        p.y += dy;
    }

    public void LevelUp(){
        level++;
    }

    public void LevelDown(){
        level--;
    }


    /**
     * Recursive draw method
    * @param lev -  the level of the koch shape
    * @param size -  the size of the koch shape
    */
    public void draw(int lev, double size) {
        // 1) define the base case
        if(lev < 0){

        // 2) define the recursive case

    }

    /**
     * Paint a snowflake
    * @param g  the graphics control
    */

    public void paint(Graphics g) {
        double size = length;

        // replace this line with recursive calls
        g.drawRect(p.x, p.y, level*5, level*5);


        // 1) set up the turtle object first

        // 2) call the recursive draw method


    }
}

【问题讨论】:

  • 在 catch 块中还打印堆栈跟踪并在此处显示。
  • currentIndex 在哪里声明和定义?
  • myShapes 在哪里声明?构造函数中的一个是局部最终变量..
  • 如需尽快获得更好的帮助,请发帖SSCCE
  • 编译该代码后,我没有看到任何运行时错误。请停止浪费大家的时间并发布一个 SSCCE 来显示问题。

标签: java swing arraylist nullpointerexception


【解决方案1】:

当您使用 ArrayList 的实际长度时,循环会更可靠:

for (int i = 0; i < myShapes.size(); i++) {

但请注意,异常也可能发生在 MySnowFlake 类的 paint 方法中。当你捕捉到一个可能由许多不同问题引起的异常时(比如 NullPointerException),你应该总是打印它的堆栈跟踪,这样你就可以看到异常实际上是在哪里抛出的:

        } catch(NullPointerException e){
            System.out.println("NullPointerException caught!!");
            e.printStackTrace();
        }

在生产软件中,最好将所有意外异常的堆栈跟踪保存到日志文件或数据库中,以便以后进行事后分析。

【讨论】:

  • 这取决于 NPE 的原因。这就是您应该打印堆栈跟踪的原因。
  • 在您更新之前我已对此发表评论。这是使用更好的方法来迭代列表的旁注。这肯定不是答案。
  • 这是评论而非答案!
  • 谢谢,我仍然收到 nullpointerexceptions,我已经包含了 MySnowFlake 类
  • 你能告诉我们你从哪里得到异常吗?也许您可以向我们展示完整的错误消息?
【解决方案2】:

能否请您更改这两行的顺序,即代替

myShapes.add(currentIndex, new MySnowFlake(e.getX(), e.getY(), currentLevel, currentLength));
currentIndex += 1;

试试这个:

currentIndex += 1;
myShapes.add(currentIndex, new MySnowFlake(e.getX(), e.getY(), currentLevel, currentLength));

【讨论】:

  • for (int i = 0; i
  • 抱歉,我发现了一个 arrayoutofbounds 异常
  • 当 currentIndex 初始化为 0 并在添加第一个元素之前递增它,那么这应该将索引 0 留空并从索引 1 开始。这应该在循环数组时立即导致 NPE。