0
lblPt1.setIcon(bd.pt1.getImage());

works while

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

throws a NullPointerException

pts[] is an array containing "Point" objects pt1 through pt24.

I would like to handle it with this for loop where pointLbls[] is an array of JLabels:

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

I have determined that it is the object that is null, not its associated image. What am I doing wrong? I am rather new to programming.

wmtkc
  • 1
  • 1
  • 1
    How did you create that pts[]-array? Give us a bit more code so we can see there the actual problem lies buried ;-) – JayC667 Nov 21 '15 at 01:02
  • I made the array using this: `public Point[] pts = {pt1, ..., pt24};` The constructor for the class in that array is in immediately instantiates the Points (it calls resetBoard): `public void resetBoard() { pt1 = new Point(1, 2); //etc for all points }` and the constructor for Point looks like this: `public Point(int color, int num) { colorValue = color; numPieces = num; GameBoard.piecesOnBoard += num; addImage(); } }` I hope that's enough to work with, thanks for the quick reply! – wmtkc Nov 21 '15 at 01:23
  • In the code you've just provided, if you really are initializing the array "public Point[] pts = {pt1, ..., pt24};" before you assign the points "pt1 = new Point(1, 2); //etc for all points }" then they will all be null. – JayC667 Nov 21 '15 at 01:44
  • if (bd == null) throw new NullPointerException("The variable 'bd' is already null!"); for (int i = 0; i < 24; i++) { final JLabel label = pointLbls[i]; if (label == null) throw new NullPointerException("The variable 'label' is already null!"); final Point pt = bd.pts[i]; if (pt == null) throw new NullPointerException("The variable 'pt' is already null!"); final Icon icon = pt.getImage(); if (icon == null) throw new NullPointerException("The variable 'icon' is already null!"); // ... and finally... label.setIcon(icon); } – JayC667 Nov 21 '15 at 01:51
  • Thank you so much! [Backgammon](http://imgur.com/Qibnm3G) is back up and running thanks to you! Why not submit a quick answer so I can give you the credit? – wmtkc Nov 21 '15 at 03:30
  • It has been marked as duplicate, and so no one can post any real answers anymore, just these short comments here... – JayC667 Nov 21 '15 at 11:12

1 Answers1

0

You can insert a Null check condition, try the code below:

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!
}
Joel Min
  • 3,168
  • 1
  • 15
  • 35
  • That's how I figured out the Point objects were null, but I can't tell why. They work fine when referenced without the array. – wmtkc Nov 21 '15 at 01:25