【问题标题】:How to prevent NullPointerException in Java when referencing object in array which works fine when referenced directly [duplicate]引用数组中的对象时如何防止Java中的NullPointerException在直接引用时工作正常[重复]
【发布时间】:2015-11-21 00:58:01
【问题描述】:
lblPt1.setIcon(bd.pt1.getImage());

工作时

lblPt1.setIcon(bd.pts[0].getImage());

抛出 NullPointerException

pts[] 是一个包含“Point”对象 pt1 到 pt24 的数组。

我想用这个 for 循环来处理它,其中 pointLbls[] 是一个 JLabels 数组:

for (int i = 0; i < 24; i++)
        pointLbls[i].setIcon(bd.pts[i].getImage());

我已经确定它是空的对象,而不是它的关联图像。 我究竟做错了什么?我对编程比较陌生。

【问题讨论】:

  • 你是如何创建 pts[]-array 的?给我们更多的代码,这样我们就可以看到真正的问题隐藏在那里;-)
  • 我使用这个创建了数组:public Point[] pts = {pt1, ..., pt24}; 该数组中的类的构造函数立即实例化 Points(它调用 resetBoard):public void resetBoard() { pt1 = new Point(1, 2); //etc for all points } 并且 Point 的构造函数如下所示: public Point(int color, int num) { colorValue = color; numPieces = num; GameBoard.piecesOnBoard += num; addImage(); } }我希望这已经足够了,感谢您的快速回复!
  • 在你刚刚提供的代码中,如果你真的在初始化数组“public Point[] pts = {pt1, ..., pt24};”在分配点“pt1 = new Point(1, 2); //etc for all points }”之前,它们都将为空。
  • if (bd == null) throw new NullPointerException("变量'bd'已经为空!"); for (int i = 0; i
  • 非常感谢!感谢您,Backgammon 已恢复正常运行!为什么不提交一个快速的答案,以便我给你功劳?

标签: java arrays nullpointerexception


【解决方案1】:

你可以插入一个空检查条件,试试下面的代码:

for(int i=0; i<24; i++){
    Point temp = bd.pts[i]; // store point in a temporary variable
    if(temp != null) // check if it is null
        pointLbls[i].setIcon(temp.getImage()); // if not null, do what you want!
}

【讨论】:

  • 这就是我发现 Point 对象为空的方式,但我不知道为什么。在没有数组的情况下引用它们可以正常工作。
猜你喜欢
  • 2017-11-14
  • 1970-01-01
  • 2012-06-23
  • 1970-01-01
  • 2013-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
相关资源
最近更新 更多