Search code examples
javanullpointerexceptionchess

Using a for-each loop within MouseClicked to getX and getY of each object


I'm a relatively unexperienced programmer who's encountered a problem during the development of a chess game in Java. I have created a Handler class which holds the individual pieces in a LinkedList. I now wish to incorporate the function of selecting the individual pieces with my mouse and changing their respective x- and y-coordinates, which is required to move them.

In my MouseClicked() method I execute a for-each loop for every Piece object in the LinkedList, and check their respective coordinates. The problem occurs here, as the loop executes the following exception occurs:

"Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException." 

How do I solve this issue?

Here follows the code in my MouseClicked():

public void mouseClicked(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    System.out.println(e.getX() + " " + e.getY());
    if(clickMode == 0)
    {
        for(Piece pi: handler.piece)
        {
            if(x >= pi.getX() && x <= pi.getX() + 75 && y >= pi.getY() && y <= pi.getY() + 75)
            {
                System.out.println("Piece Selected");
                pi.isSelected = true;
                clickMode = 1;
            }
        }
    }
    else
    {
        for(Piece pi: handler.piece)
        {
            if(pi.isSelected == true)
            {
                System.out.println("Piece Moved");
                pi.setX(x);
                pi.setY(y);

                pi.isSelected = false;
            }                               
        }
        clickMode = 0;
    }               
}

Solution

  • The most likely cause of your NullPointerException is that one of the locations in your LinkedList does not contain an instantiated piece. That, or your handler instance has not been instantiated. Make sure every object you're using has been constructed.