【问题标题】:Issue in initializing an array of objects初始化对象数组的问题
【发布时间】:2012-12-28 09:10:48
【问题描述】:

当我尝试从普通数组中检索对象时遇到空指针异常。首先,我用 10 个Line 对象初始化数组,然后设置数组中每个对象的值。但是当我检索任何对象的值时,我发现它是 0。为什么会这样?

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class LineArrayLimt extends Applet
    implements MouseListener, MouseMotionListener {

    int width, height;
    int x, y, lineCounter;    // the coordinates of the upper-left corner of the box
    int mx, my;  // the most recently recorded mouse coordinates
    int new_mx;
    int new_my;
    Thread th;
    boolean isMouseDragging = false, isStored;
    Line[] lines = new Line[10];

    class Line {

        Line() {
        }

        Line(int x1, int y1, int x2, int y2) {
            this.x1 = x1;
            this.y1 = y1;
            this.x2 = x2;
            this.y2 = y2;
        }
        private int x1, y1, x2, y2;

        public void setX1(int x) {
            this.x1 = x;
        }

        public void setY1(int y) {
            this.y1 = y;
        }

        public void setX2(int x) {
            this.x2 = x;
        }

        public void setY2(int y) {
            this.y2 = y;
        }

        public int getX1() {
            return x1;
        }

        public int getY1() {
            return y1;
        }

        public int getX2() {
            return x2;
        }

        public int getY2() {
            return y2;
        }
    }

    public void init() {
        width = getSize().width;
        height = getSize().height;
        setBackground(Color.black);
        addMouseListener(this);
        addMouseMotionListener(this);
        for (int i = 0; i < lines.length; i++) {
            lines[i] = new Line();
        }

    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public void mouseClicked(MouseEvent e) {
    }

    public void mousePressed(MouseEvent e) {
        System.out.println("-----------------Mouse Pressed------------------------");
        mx = e.getX();
        my = e.getY();



    }

    public void mouseReleased(MouseEvent e) {
        System.out.println("-----------------Mouse Released------------------------");
        if (isMouseDragging) {
            if (lineCounter != lines.length - 1) {
                lines[lineCounter].setX1(mx);
                lines[lineCounter].setY1(my);
                lines[lineCounter].setX2(new_mx);
                lines[lineCounter].setY2(new_my);
                lineCounter++;
                if (lines[lineCounter] != null) {
                    System.out.println("-----------------First Object------------------------" + lines[lineCounter].getX1() + " " + lines[lineCounter].getY1() + " " + lines[lineCounter].getX2() + " " + lines[lineCounter].getY1());
                }


            }

        }
        isMouseDragging = false;

    }

    public void mouseMoved(MouseEvent e) {
    }

    public void mouseDragged(MouseEvent e) {
        System.out.println("-----------------Mouse Dragged------------------------");
        isMouseDragging = true;
        new_mx = e.getX();
        new_my = e.getY();
        if (new_mx <= 35) {
            new_mx = 35;
        }
        if (new_mx > width - 40) {
            new_mx = width - 40;
        }
        if (new_my > height - 40) {
            new_my = height - 40;
        }
        if (new_my < 35) {
            new_my = 35;
        }
        repaint();

    }

    public void paint(Graphics g) {
        System.out.println("-----------------Line No." + lineCounter + " is inside paint------------------------");
        g.setColor(Color.RED);
        if (isMouseDragging) {
            System.out.println("-----------------Paint while dragging------------------------");
            g.drawLine(mx, my, new_mx, new_my);
            if (lineCounter != lines.length - 1) {
                //if(lines[lineCounter]!=null){
                g.drawLine(lines[lineCounter].getX1(), lines[lineCounter].getY1(), lines[lineCounter].getX2(), lines[lineCounter].getX2());
                System.out.println("*************" + lines[lineCounter].getX1() + lines[lineCounter].getY1() + lines[lineCounter].getX2() + lines[lineCounter].getX2());
                //}
            }
        }
    }
}

【问题讨论】:

  • 在标记的行尝试使用trycatch函数
  • @goravine:绝对不是。您几乎应该永远故意捕获 NullPointerException。
  • 很难阅读您的代码,因为它的格式非常糟糕。请更加努力地以尽可能易于阅读的方式编写您的问题。 (我相信你也可以大大减少这个例子。)
  • 这里有一些见解供您浏览 NPE article1, article2
  • 参见stackoverflow.com/questions/1922677/… 了解类似 NPE 行为的“最小测试用例”(不过,我会使用 Jon 建议的 List。)

标签: java arrays nullpointerexception


【解决方案1】:

问题在于,在 init 中,您将 lines 初始化为一个包含 10 个空引用的数组:

lines = new Line[10];

然后在paint 中,您正在使用该空引用:

if (lineCounter != lines.length - 1) {
    g.drawLine(lines[lineCounter].getX1(),
               lines[lineCounter].getY1(),
               lines[lineCounter].getX2(),
               lines[lineCounter].getY2());
}

lines.length始终为 10 - 这不是数组中非空引用的数量。这不是你添加的行数,或者类似的东西。 (说实话,不清楚您的 if 条件试图达到什么目的。)

您最好改用List&lt;Line&gt;。然后在paint 你可以使用:

for (Line line : lines) {
    ...
}

...在mouseReleased 中,您只需使用:

lines.add(new Line(...));

另请注意,Line 没有理由成为内部类。使其成为静态嵌套类或顶级(非嵌套)类。

【讨论】:

  • 或在循环中显式初始化它。 [lines[i] = new Line();] (i 从 0 到 9)
  • @TJ-:我看不出这会有什么用处,因为在用户绘制任何线条之前,没有任何应该绘制的线条......
  • 哦,我的错。我没有阅读问题,我只是指使用lines = new Line[10];
  • 好的,但是在init方法中用10个Line类型的元素初始化数组有什么问题,在mouseReleased中我向数组添加了元素,为什么它仍然保持NULLS?我编辑了代码,我认为问题在于绘画仅在小程序第一次启动时才访问空引用,所以我添加了一个额外的条件来绘画以访问数组元素
  • @Eslam:在init() 中,您不是使用10 个Line 引用初始化数组。您正在创建一个最初包含 10 个 null 引用的数组。您可以创建 10 个Line 对象,但您并不想绘制任何线条,因此这样做没有意义。从根本上说,我认为您需要重新审视数组创建行为 - 但我也强烈建议您使用列表来代替......
【解决方案2】:

您是否检查过该行是否确实添加到mouseReleased 中的数组中?

【讨论】:

  • 我的意思是,如果由于某种原因,方法中的条件总是为假,那么数组的元素将保持为空。只是一个非常基本的健全性检查。
【解决方案3】:

问题是您只在mouseReleased() 函数中填充数组,而paint 方法不等待鼠标释放。所以当鼠标没有释放时,paint() 方法会尝试画线。

您只需取消注释您的支票 if(lines[lineCounter]!=null) 并尝试,它应该可以工作。

如果您想实现其他目标,请告诉我们

【讨论】:

    猜你喜欢
    • 2016-01-06
    • 2014-02-27
    • 2018-06-22
    • 1970-01-01
    • 2017-02-16
    • 2018-02-15
    • 2017-02-18
    相关资源
    最近更新 更多